<?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[ Functional Programming - 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[ Functional Programming - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:30:34 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/functional-programming/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Helpful Built-in Functions in C++ that All Devs Should Know ]]>
                </title>
                <description>
                    <![CDATA[ Built-in functions in C++ are those functions that are part of the C++ standard libraries. These functions are designed to provide common and essential functionality that is often required in programming. In this article, we will look at some of the ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/helpful-built-in-functions-in-cpp/</link>
                <guid isPermaLink="false">687fc93c8ff83d5b41883c1e</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ AYUSH MISHRA ]]>
                </dc:creator>
                <pubDate>Tue, 22 Jul 2025 17:24:12 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753105870543/7bdb3c7e-873b-46a2-bdbd-0d881aacedfc.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Built-in functions in C++ are those functions that are part of the C++ standard libraries. These functions are designed to provide common and essential functionality that is often required in programming.</p>
<p>In this article, we will look at some of the most commonly used built-in functions in C++ so you can start using them in your code.</p>
<h3 id="heading-what-well-cover">What we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-the-sqrt-function">The <code>sqrt()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-pow-function">The <code>pow()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-sort-function">The <code>sort()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-find-function">The <code>find()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-binarysearch-function">The <code>binarysearch()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-max-function">The <code>max()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-min-function">The <code>min()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-swap-function">The <code>swap()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-toupper-function">The <code>toupper()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-tolower-function">The <code>tolower()</code> Function</a></p>
</li>
</ol>
<h2 id="heading-the-sqrt-function">The <code>sqrt()</code> Function</h2>
<p>You use the <code>sqrt()</code> function to determine the square root of the value of type double. It is defined inside the <code>&lt;cmath&gt;</code> header file.</p>
<h3 id="heading-syntax"><strong>Syntax:</strong></h3>
<pre><code class="lang-plaintext">sqrt (n)
</code></pre>
<p><strong>Parameter:</strong> This function takes only one parameter of type double which is a number we want to find the square root of.</p>
<p><strong>Return Type:</strong> The square root of the value of type double.</p>
<h3 id="heading-example-code">Example Code</h3>
<p>Let’s look at an example so you can see how this function works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ program to see the use of sqrt() function</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cmath&gt;     </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;  </span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;  
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">double</span> x = <span class="hljs-number">100</span>;

    <span class="hljs-keyword">double</span> answer;

    <span class="hljs-comment">// Use the sqrt() function to calculate the square root of the number</span>
    answer = <span class="hljs-built_in">sqrt</span>(x);

    <span class="hljs-comment">// Print the result </span>
    <span class="hljs-built_in">cout</span> &lt;&lt; answer &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>10</p>
<h2 id="heading-the-pow-function"><strong>The</strong> <code>pow()</code> <strong>Function</strong></h2>
<p>You use the <code>pow()</code> function to find the value of the given number raised to some power. This function is also defined inside the <code>&lt;cmath&gt;</code> header file.</p>
<h3 id="heading-syntax-1"><strong>Syntax:</strong></h3>
<pre><code class="lang-plaintext">double pow(double x, double y);
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>x:</strong> The base number.</p>
</li>
<li><p><strong>y:</strong> The exponential power.</p>
</li>
</ul>
<p><strong>Return Type:</strong> value of <strong>x</strong> raised to the power <strong>y</strong>.</p>
<h3 id="heading-example-code-1">Example Code:</h3>
<p>Let’s look at an example to see how this works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ program to see the use of the pow() function</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cmath&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
 <span class="hljs-comment">// Declare an integer variable 'base' </span>
    <span class="hljs-keyword">int</span> base = <span class="hljs-number">5</span>;

<span class="hljs-comment">// Declare an integer variable 'exponent' </span>
    <span class="hljs-keyword">int</span> exponent = <span class="hljs-number">3</span>;

<span class="hljs-comment">// pow(5, 3) means 5^3 which is 5*5*5 = 125</span>
<span class="hljs-comment">// Use the pow() function to calculate base raised to the power of exponent</span>
    <span class="hljs-keyword">int</span> answer = <span class="hljs-built_in">pow</span>(base, exponent);

<span class="hljs-comment">// output the result</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; answer &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>Output:</p>
<p>125</p>
<h2 id="heading-the-sort-function">The <code>sort()</code> Function</h2>
<p>The <code>sort()</code> function is part of STL's <code>&lt;algorithm&gt;</code> header. It is a function template that you can use to sort the random access containers, such as vectors, arrays, and so on.</p>
<h3 id="heading-syntax-2">Syntax:</h3>
<pre><code class="lang-plaintext">sort (arr , arr + n, comparator)
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>arr:</strong> The pointer or iterator to the first element of the array.</p>
</li>
<li><p><strong>arr + n:</strong> The pointer to the imaginary element next to the last element of the array.</p>
</li>
<li><p><strong>comparator:</strong> The unary predicate function that is used to sort the value in some specific order. The default value of this sorts the array in ascending order.</p>
</li>
</ul>
<p><strong>Return Value:</strong> This function does not return any value.</p>
<h3 id="heading-example-code-2">Example Code:</h3>
<p>Let’s look at an example:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;     </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;    // Header file that includes the sort() function</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;    

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Declare and initialize an integer array with unsorted elements</span>
    <span class="hljs-keyword">int</span> arr[] = { <span class="hljs-number">13</span>, <span class="hljs-number">15</span>, <span class="hljs-number">12</span>, <span class="hljs-number">14</span>, <span class="hljs-number">11</span>, <span class="hljs-number">16</span>, <span class="hljs-number">18</span>, <span class="hljs-number">17</span> };

    <span class="hljs-comment">// Calculate the number of elements in the array</span>
    <span class="hljs-keyword">int</span> n = <span class="hljs-keyword">sizeof</span>(arr) / <span class="hljs-keyword">sizeof</span>(arr[<span class="hljs-number">0</span>]);

    <span class="hljs-comment">// Use the built-in sort() function from the algorithm library</span>
    sort(arr, arr + n);

    <span class="hljs-comment">// Print the sorted array using a loop</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; n; ++i)
        <span class="hljs-built_in">cout</span> &lt;&lt; arr[i] &lt;&lt; <span class="hljs-string">" "</span>;  

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>11 12 13 14 15 16 17 18</p>
<h2 id="heading-the-find-function">The <code>find()</code> Function</h2>
<p>The <code>find()</code> function is also part of the STL <code>&lt;algorithm&gt;</code> library. You use this function to find a value in the given range. You can use it with both sorted and unsorted datasets as it implements a linear search algorithm.</p>
<h3 id="heading-syntax-3"><strong>Syntax:</strong></h3>
<pre><code class="lang-plaintext">find(startIterator, endIterator, key)
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>startIterator:</strong> Iterates to the beginning of the range.</p>
</li>
<li><p><strong>endIterator:</strong> Iterates to the end of the range.</p>
</li>
<li><p><strong>key:</strong> The value to be searched.</p>
</li>
</ul>
<p><strong>Return Value:</strong> If the element is found, then the iterator is set to the element. Otherwise, it iterates to the end.</p>
<h3 id="heading-example-code-3">Example Code:</h3>
<p>Let’s look at an example to better understand how it works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ program to see the the use of the find() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;   // Required for the find() function</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;    </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;      </span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;   

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Initialize a vector </span>
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; dataset{ <span class="hljs-number">12</span>, <span class="hljs-number">28</span>, <span class="hljs-number">16</span>, <span class="hljs-number">7</span>, <span class="hljs-number">33</span>, <span class="hljs-number">43</span> };

    <span class="hljs-comment">// Use the find() function to search for the value 7</span>
    <span class="hljs-keyword">auto</span> index = find(dataset.begin(), dataset.end(), <span class="hljs-number">7</span>);

    <span class="hljs-comment">// Check if the element was found</span>
    <span class="hljs-keyword">if</span> (index != dataset.end()) {
        <span class="hljs-comment">// If found, print the position (index) by subtracting the starting iterator</span>
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The element is found at the "</span>
             &lt;&lt; index - dataset.begin() &lt;&lt; <span class="hljs-string">"nd index"</span>;
    }
    <span class="hljs-keyword">else</span> {
        <span class="hljs-comment">// If not found</span>
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Element not found"</span>;
   }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>The element is found at the 3rd index</p>
<h2 id="heading-the-binarysearch-function">The <code>binary_search()</code> Function</h2>
<p>The <code>binary_search()</code> function is also used to find an element in the range – but this function implements binary search instead of linear search as compared to the <code>find()</code> function. It’s also faster than the <code>find()</code> function, but you can only use it on sorted datasets with random access. It’s defined inside the <code>&lt;algorithm&gt;</code> header file.</p>
<h3 id="heading-syntax-4"><strong>Syntax:</strong></h3>
<pre><code class="lang-plaintext">binary_search (starting_pointer , ending_pointer , target);
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>starting_pointer:</strong> Pointer to the start of the range.</p>
</li>
<li><p><strong>ending_pointer:</strong> Pointer to the element after the end of the range.</p>
</li>
<li><p><strong>target:</strong> Value to be searched in the dataset.</p>
</li>
</ul>
<p><strong>Return Value:</strong></p>
<ul>
<li><p>Returns true if the target is found.</p>
</li>
<li><p>Else return false.</p>
</li>
</ul>
<h3 id="heading-example-code-4">Example Code:</h3>
<p>Let’s check out an example to see how it works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ program for the binary_search() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;   </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;    </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;      </span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;   

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Initialize a sorted vector of integers</span>
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; arr = { <span class="hljs-number">56</span>, <span class="hljs-number">57</span>, <span class="hljs-number">58</span>, <span class="hljs-number">59</span>, <span class="hljs-number">60</span>, <span class="hljs-number">61</span>, <span class="hljs-number">62</span> };

    <span class="hljs-comment">// binary_search() works only on sorted containers</span>
    <span class="hljs-keyword">if</span> (binary_search(arr.begin(), arr.end(), <span class="hljs-number">62</span>)) {
        <span class="hljs-comment">// If found, print that the element is present</span>
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-number">62</span> &lt;&lt; <span class="hljs-string">" is present in the vector."</span>;
    }
    <span class="hljs-keyword">else</span> {
        <span class="hljs-comment">// If not found, print that the element is not present</span>
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-number">16</span> &lt;&lt; <span class="hljs-string">" is not present in the vector"</span>;
    }

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>Output:</p>
<p>62 is present in the vector.</p>
<h2 id="heading-the-max-function">The <code>max()</code> Function</h2>
<p>You can use the <code>std::max()</code> function to compare two numbers and find the bigger one between them. It’s also defined inside the <code>&lt;algorithm&gt;</code> header file.</p>
<h3 id="heading-syntax-5">Syntax:</h3>
<pre><code class="lang-plaintext">max (a , b)
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>a:</strong> First number</p>
</li>
<li><p><strong>b:</strong> Second number</p>
</li>
</ul>
<p><strong>Return Value:</strong></p>
<ul>
<li><p>This function returns the larger number between the two numbers <strong>a</strong> and <strong>b.</strong></p>
</li>
<li><p>If the two numbers are equal, it returns the first number.</p>
</li>
</ul>
<h3 id="heading-example-code-5">Example Code:</h3>
<p>Here’s an example:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// max() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;  </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;   </span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Declare two integer variables</span>
    <span class="hljs-keyword">int</span> a = <span class="hljs-number">8</span> ;
    <span class="hljs-keyword">int</span> b = <span class="hljs-number">10</span> ;

    <span class="hljs-comment">// Use the max() function to find the larger number between a and b</span>
    <span class="hljs-keyword">int</span> maximum = max(a, b);

    <span class="hljs-comment">// Display the result with a meaningful message</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The maximum of "</span> &lt;&lt; a &lt;&lt; <span class="hljs-string">" and "</span> &lt;&lt; b &lt;&lt; <span class="hljs-string">" is: "</span> &lt;&lt; maximum &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>The maximum of 8 and 10 is: 10</p>
<h2 id="heading-the-min-function">The <code>min()</code> Function</h2>
<p>You can use the <code>std::min()</code> function to compare two numbers and find the smaller of the two. It’s also defined inside the <code>&lt;algorithm&gt;</code> header file.</p>
<h3 id="heading-syntax-6">Syntax:</h3>
<pre><code class="lang-plaintext">min (a , b)
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>a:</strong> First number</p>
</li>
<li><p><strong>b:</strong> Second number</p>
</li>
</ul>
<p><strong>Return Value:</strong></p>
<ul>
<li><p>This function returns the smaller number between the two numbers <strong>a</strong> and <strong>b.</strong></p>
</li>
<li><p>If the two numbers are equal, it returns the first number.</p>
</li>
</ul>
<h3 id="heading-example-code-6">Example Code:</h3>
<p>Here’s an example:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// use of the min() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;  // For the built-in min() function</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;   </span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Declare two integer variables to store user input</span>
    <span class="hljs-keyword">int</span> a = <span class="hljs-number">4</span> ;
    <span class="hljs-keyword">int</span> b = <span class="hljs-number">8</span> ;

    <span class="hljs-comment">// Use the min() function to find the smaller </span>
    <span class="hljs-keyword">int</span> smallest = min(a, b);

    <span class="hljs-comment">// Display the result </span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The smaller number between "</span> &lt;&lt; a &lt;&lt; <span class="hljs-string">" and "</span> &lt;&lt; b &lt;&lt; <span class="hljs-string">" is: "</span> &lt;&lt; smallest &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>The smaller number between 4 and 8 is: 4</p>
<h2 id="heading-the-swap-function">The <code>swap()</code> Function</h2>
<p>The <code>std::swap()</code> function lets you swap two values. It’s defined inside <code>&lt;algorithm&gt;</code> header file.</p>
<h3 id="heading-syntax-7"><strong>Syntax:</strong></h3>
<pre><code class="lang-plaintext">swap(a , b);
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>a:</strong> First number</p>
</li>
<li><p><strong>b:</strong> Second number</p>
</li>
</ul>
<p><strong>Return Value:</strong> This function does not return any value.</p>
<h3 id="heading-example">Example:</h3>
<p>Here’s how it works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">//  use of the swap() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;  // For the built-in swap() function</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;   </span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">int</span> firstNumber = <span class="hljs-number">8</span> ;
    <span class="hljs-keyword">int</span> secondNumber = <span class="hljs-number">9</span> ;


    <span class="hljs-comment">// Use the built-in swap() function to exchange values</span>
    swap(firstNumber, secondNumber);

    <span class="hljs-comment">// Display values after swapping</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"After the swap:"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; firstNumber &lt;&lt; <span class="hljs-string">" "</span> &lt;&lt; secondNumber &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>After the swap:</p>
<p>9 8</p>
<h2 id="heading-the-tolower-function">The <code>tolower()</code> Function</h2>
<p>You can use the <code>tolower()</code> function to convert a given alphabet character to lowercase. It’s defined inside the <code>&lt;cctype&gt;</code> header.</p>
<h3 id="heading-syntax-8">Syntax:</h3>
<pre><code class="lang-plaintext">tolower (c);
</code></pre>
<p><strong>Parameter(s):</strong></p>
<ul>
<li><strong>c:</strong> The character to be converted.</li>
</ul>
<p><strong>Return Value:</strong></p>
<ul>
<li><p>Lowercase of the character c.</p>
</li>
<li><p>Returns c if c is not a letter.</p>
</li>
</ul>
<h3 id="heading-example-code-7">Example Code:</h3>
<p>Here’s how it works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ program</span>

<span class="hljs-comment">// use of tolower() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cctype&gt;     </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;   </span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Declare and initialize a string with uppercase characters</span>
    <span class="hljs-built_in">string</span> str = <span class="hljs-string">"FRECODECAMP"</span>;

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span>&amp; a : str) {
        a = <span class="hljs-built_in">tolower</span>(a);
    }

    <span class="hljs-comment">// Print the modified string </span>
    <span class="hljs-built_in">cout</span> &lt;&lt; str;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>freecodecamp</p>
<h2 id="heading-the-toupper-function">The <code>toupper()</code> Function</h2>
<p>You can use the <code>toupper()</code> function to convert the given alphabet character to uppercase. It’s defined inside the <code>&lt;cctype&gt;</code> header.</p>
<h3 id="heading-syntax-9">Syntax:</h3>
<pre><code class="lang-plaintext">toupper (c);
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><strong>c:</strong> The character to be converted.</li>
</ul>
<p><strong>Return Value</strong></p>
<ul>
<li><p>Uppercase of the character c.</p>
</li>
<li><p>Returns c if c is not a letter.</p>
</li>
</ul>
<h3 id="heading-example-code-8">Example Code:</h3>
<p>Here’s how it works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// use of toupper() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cctype&gt;     </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;   </span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Declare and initialize a string </span>
    <span class="hljs-built_in">string</span> str = <span class="hljs-string">"freecodecamp"</span>;

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span>&amp; a : str) {
        a = <span class="hljs-built_in">toupper</span>(a);
    }

    <span class="hljs-comment">// Output the converted uppercase string</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; str;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>FREECODECAMP</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Inbuilt functions are helpful tools in competitive programming and in common programming tasks. These help in improving code readability and enhance the efficiency of code. In the above article, we discussed some very useful common inbuilt functions. Some common inbuilt functions are <code>max()</code>, <code>min()</code>, <code>sort()</code>, and <code>sqrt()</code>, etc. By using these inbuilt libraries, we can reduce boilerplate code and speed up the process of software development. These help in writing more concise, reliable, and maintainable C++ programs.</p>
<p>And if you'd like to support me and my work directly so I can keep creating these tutorials, <a target="_blank" href="https://paypal.me/ayushM010">you can do so here</a>. Thank you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An Animated Introduction to Elixir ]]>
                </title>
                <description>
                    <![CDATA[ Elixir is a dynamic, functional programming language designed for building scalable and maintainable applications. It leverages the battle-tested Erlang VM, known for running low-latency, distributed, and fault-tolerant systems. Elixir is based on an... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-animated-introduction-to-elixir/</link>
                <guid isPermaLink="false">682f44e3dcb21c615cf1a12d</guid>
                
                    <category>
                        <![CDATA[ Elixir ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mark Mahoney ]]>
                </dc:creator>
                <pubDate>Thu, 22 May 2025 15:38:11 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747923637406/e7ad8796-6269-4260-b500-226e445140ce.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><a target="_blank" href="https://elixir-lang.org/">Elixir</a> is a dynamic, functional programming language designed for building scalable and maintainable applications. It leverages the battle-tested Erlang VM, known for running low-latency, distributed, and fault-tolerant systems.</p>
<p>Elixir is based on another language called <a target="_blank" href="https://www.erlang.org/">Erlang</a>. Erlang was developed by Ericsson in the 1980s for telecom applications requiring extreme reliability and availability. It includes built-in support for concurrency, distribution, and fault-tolerance. Elixir, created by José Valim, brings a more approachable and expressive syntax to the Erlang VM. It lowers the barrier to entry for using Erlang's powerful features.</p>
<p>In Elixir, functions are the primary building blocks of programs, similar to how classes and methods are the core units in object-oriented languages. But instead of modeling behavior through stateful objects, functional languages like Elixir treat computation as a series of pure functions that take input and produce output without side effects.</p>
<p>This paradigm offers several benefits:</p>
<ul>
<li><p>Immutability: Data is immutable by default. Once a variable is bound, it can't be changed. This avoids hard to track bugs caused by side effects.</p>
</li>
<li><p>Functions as first-class citizens: Functions can be assigned to variables, passed as arguments, and returned from other functions. This enables powerful abstractions and code reuse.</p>
</li>
<li><p>Pattern matching: Elixir uses pattern matching to bind variables, unpack data structures, and control program flow. This leads to concise and declarative code.</p>
</li>
<li><p>Recursion: Looping is typically achieved through recursion. Elixir optimizes recursive calls to avoid stack overflow issues.</p>
</li>
</ul>
<p>While functional programming requires a shift in thinking, it can lead to more predictable and maintainable systems. Elixir makes this paradigm friendly and accessible.</p>
<p>One of Elixir's standout features is its concurrency model. It uses lightweight processes to achieve massive scalability:</p>
<ul>
<li><p>Processes are isolated and share no memory, communicating only via message passing.</p>
</li>
<li><p>The Erlang VM can run millions of processes concurrently on a single machine.</p>
</li>
<li><p>Fault-tolerance is achieved by supervising and restarting failed processes.</p>
</li>
</ul>
<p>This architecture enables building distributed, real-time systems that efficiently use modern multi-core hardware.</p>
<h2 id="heading-an-animated-introduction-to-elixir"><strong>An Animated Introduction to Elixir</strong></h2>
<p>To make Elixir's functional and concurrent nature more approachable, I developed an interactive tutorial called "An Animated Introduction to Elixir". It uses annotated code playbacks to walk through key language features step-by-step. From basic syntax to advanced topics like concurrency, each concept is explained through code and accompanying visuals.</p>
<p>You can access the free 'book' of code playbacks here: <a target="_blank" href="https://playbackpress.com/books/exbook">https://playbackpress.com/books/exbook</a>.</p>
<p>For more info about code playbacks, you can watch a short demo:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/uYbHqCNjVDM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>Part 1 of the book focuses on core Elixir – syntax basics, pattern matching, functions and modules, key data structures like tuples, maps, lists, functional concepts like closures, recursion, enumeration, and efficient immutability.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/1">1.1 Hello Elixir!!!</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/2">1.2 Numbers and the Match Operator</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/3">1.3 Functions and More Matching</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/4">1.4 Modules and More Matching with SimpleMath</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/5">1.5 Closures</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/6">1.6 Ranges and the Enum Module</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/7">1.7 Tuples</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/8">1.8 Maps</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/9">1.9 SimpleDateFormatter Module with Maps</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/10">1.10 Lists, Matching, and Recursion</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/11">1.11 Poker Probabilities</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/1/12">1.12 Recursion in Elixir</a></p>
</li>
</ul>
<p>Part 2 explores Elixir's concurrency model – working with processes, message passing between processes, dividing work across processes, and real-world examples and benchmarking. The concepts are applied to practical problems like estimating poker probabilities and generating calendars.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/2/1">2.1 Adding Tests to the Mix</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/2/2">2.2 Process Basics</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/2/3">2.3 Prime Sieve</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/2/4">2.4 Calendar with Processes</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook/chapter/2/5">2.5 Poker with Processes</a></p>
</li>
</ul>
<h2 id="heading-why-learn-elixir">Why Learn Elixir?</h2>
<p>Learning Elixir is beneficial for programmers for several compelling reasons. Elixir's functional paradigm and immutable data structures promote writing cleaner, more predictable, and maintainable code.</p>
<p>Its actor-based concurrency model, built on the robust Erlang VM, enables developing highly scalable, fault-tolerant, and distributed systems that can efficiently leverage multi-core processors and handle massive numbers of simultaneous users. Also, Elixir has a friendly, expressive syntax that lowers the barrier to entry for using these powerful features.</p>
<p>Finally, Elixir has a rapidly growing, vibrant community and ecosystem. For example, the Elixir ecosystem includes powerful web frameworks like <a target="_blank" href="https://www.phoenixframework.org/">Phoenix</a> for building scalable web applications, <a target="_blank" href="https://nerves-project.org/">Nerves</a> for creating embedded software for devices, and <a target="_blank" href="https://hexdocs.pm/ecto/Ecto.html">Ecto</a> for writing database queries and interacting with different databases.</p>
<p>If you have any questions or feedback, I'd love to hear it. Comments and feedback are welcome anytime: <a target="_blank" href="mailto:mark@playbackpress.com">mark@playbackpress.com</a>.</p>
<p>If you'd like to support my work and help keep Playback Press free for all, consider donating using <a target="_blank" href="https://github.com/sponsors/markm208">GitHub Sponsors</a>. I use all of the donations for hosting costs. Your support helps me continue creating educational content like this. Thank you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An Animated Introduction to Clojure – Learn Clojure Programming Basics ]]>
                </title>
                <description>
                    <![CDATA[ This tutorial introduces the programming language, Clojure. Clojure is an awesome functional programming language that runs on Java's Virtual Machine (JVM). It is sometimes called a LISP, which is short for 'LISt Processing'. You'll need to have some... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-clojure-programming-basics/</link>
                <guid isPermaLink="false">67f7044b8d28cad83fb095a2</guid>
                
                    <category>
                        <![CDATA[ Clojure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ jvm ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mark Mahoney ]]>
                </dc:creator>
                <pubDate>Wed, 09 Apr 2025 23:35:39 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744240649396/3e68ef22-3109-4b43-841e-e947f1821a76.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>This tutorial introduces the programming language, Clojure. <a target="_blank" href="https://clojure.org/">Clojure</a> is an awesome functional programming language that runs on Java's Virtual Machine (JVM). It is sometimes called a LISP, which is short for '<strong>LIS</strong>t <strong>P</strong>rocessing'.</p>
<p>You'll need to have some previous programming experience in another language to get the most out of this tutorial. Clojure is so different from most imperative programming languages that it doesn't really matter where you are coming from as long as you know the basics (variables, if statements, loops, and functions).</p>
<p>If you are looking for a complete beginner's guide to programming, you can find some of my other programming content below.</p>
<p>Here, I will cover functions, data structures, immutability, closures, tail recursion, lazy sequences, macros, and concurrency.</p>
<p>Clojure is a functional programming language. In it, the function is king and data is immutable. This may be a different paradigm than you are used to, but there are some compelling reasons to use it. Clojure's immutability is particularly good for programs that need to take advantage of modern hardware on laptops and mobile phones (multiple processors sharing a single memory).</p>
<p>Clojure runs on the <a target="_blank" href="https://en.wikipedia.org/wiki/Java_virtual_machine">JVM</a>. It can be difficult to set up Clojure because it involves installing Java, Leiningen, and sometimes an editor plugin. To make things easier, I recommend starting with a web-based IDE. There is no easier way to start programming in Clojure than using <a target="_blank" href="https://replit.com/">replit</a>. I recommend using it to write your first programs in Clojure. If you feel up to it, check out <a target="_blank" href="https://clojure.org/guides/install_clojure">these docs</a> to get started on your own machine.</p>
<p>Even if you don't use Clojure every day, learning it will change how you think about programming. It will help you understand recursion, higher-order functions, and data transformations in a new way. These ideas transfer well to other languages like JavaScript, Python, or Rust. In short, learning Clojure will make you a better programmer.</p>
<h3 id="heading-code-playbacks"><strong>Code Playbacks</strong></h3>
<p>This material will not be delivered like traditional online tutorials or video series. Each section includes links to interactive <strong>code playbacks</strong> that visually animate changes made to a program in a step-by-step manner, helping you understand how it was written.</p>
<p>A code playback shows how a program evolves by replaying all the steps in its development. It has an author-supplied narrative, screenshots, whiteboard-style drawings, and self-grading multiple choice questions to make the learning process more dynamic and interactive.</p>
<p>Here's a short YouTube video explaining how to view a code playback:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/uYbHqCNjVDM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h3 id="heading-playback-press"><strong>Playback Press</strong></h3>
<p><a target="_blank" href="https://playbackpress.com/books">Playback Press</a> is a platform for sharing interactive code walkthroughs that I created. I’m Mark, by the way, a professor of computer science. These books provide interactive programming lessons through step-by-step animations, AI tutoring, and quizzes.</p>
<p>If you want to see the full Clojure 'book', you can go here:</p>
<blockquote>
<p><a target="_blank" href="https://playbackpress.com/books/cljbook">An Animated Introduction to Clojure</a>, by Mark Mahoney</p>
</blockquote>
<p>I also built <a target="_blank" href="https://markm208.github.io/">Storyteller</a>, the free and open-source tool that powers code playbacks.</p>
<h3 id="heading-ai-tutor"><strong>AI Tutor</strong></h3>
<p>When viewing a code playback, you can ask an AI tutor about the code. It answers questions clearly and patiently, making it a helpful resource for learners. You can also ask the AI tutor to generate new self-grading multiple-choice questions to test your knowledge of what you are learning.</p>
<p>To access the AI tutor and self-grading quizzes, simply create a free account on Playback Press and add the <a target="_blank" href="https://playbackpress.com/books/cljbook">book</a> to your bookshelf.</p>
<h3 id="heading-table-of-contents"><strong>Table of Contents</strong></h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-introduction-to-clojure">Introduction to Clojure</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-functions">Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-closures">Closures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-recursion">Recursion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-lazy-sequences">Lazy Sequences</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-macros">Macros</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-concurrency">Concurrency</a></p>
</li>
</ul>
<h2 id="heading-introduction-to-clojure"><strong>Introduction to Clojure</strong></h2>
<p>These first few programs show how to print to the screen, perform basic arithmetic, and store some data. Go through each of these now:</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/1/1">Hello World!!!</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/1/2">Readers/evaluators and simple arithmetic</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/1/3">Dog age converter</a></p>
</li>
</ul>
<p>This program shows how to use the Java capability that it built into to the JVM.</p>
<ul>
<li><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/1/4">Java interoperability</a></li>
</ul>
<p>These programs show some basic data structures in Clojure and how they are immutable.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/1/5">Clojure data structures</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/1/6">Efficient immutability (more with data structures)</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice"><strong>Hands-On Practice</strong></h3>
<p><strong>Problem 1</strong></p>
<p>Write a Clojure program that prompts the user for the length and width of a wooden board in inches. Then display the number of whole square feet that are in the board. For example, if the height is 27 inches and the width is 34 inches, then the number of square feet is 6.375.</p>
<p><strong>Problem 2</strong></p>
<p>Write a program that creates an empty list and use <code>def</code> to store a reference to it called <code>empty-list</code>. Use <code>cons</code> to add your name to it and store it in a new list called <code>my-name</code>.</p>
<p>Use <code>conj</code> to add all of your siblings to a list called <code>me-and-my-siblings</code> (if you don't have any or don't have that many you can use some of the <a target="_blank" href="https://en.wikipedia.org/wiki/Kardashian_family#Members_of_the_Kardashian-Jenner_Family">Kardashians</a>).</p>
<p>Print all the names in <code>me-and-my-siblings</code>. Then print the third name on the list <code>me-and-my-siblings</code>.</p>
<p>Create a map with all of your siblings' names as keys and their birth years as values. Use <code>assoc</code> to add your name and birth year to the map. Use the map to print everyone's name and their age in the year 2050.</p>
<p><strong>Problem 3</strong></p>
<p>Create a map with the number of days in each of the months called <code>days-in-months</code>. Use Clojure keywords like <code>:jan</code> and <code>:feb</code> as the keys and the number of days in the months as the values.</p>
<p>Create a second map from the first that has 29 days for February. Call this one <code>days-in-months-leapyear</code>. Make sure to do this efficiently, use <code>assoc</code> to create a new value for February. Finally, print each of the maps.</p>
<h2 id="heading-functions"><strong>Functions</strong></h2>
<p>Next, I'll discuss creating and calling functions in Clojure. Clojure is a functional programming language so this is a pretty important topic.</p>
<p>The first two programs show how to write functions in Clojure.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/2/1">Functions in Clojure</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/2/2">Fizz Buzz</a></p>
</li>
</ul>
<p>This program shows how to use a map to encapsulate data along with some functions that manipulate the data.</p>
<ul>
<li><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/2/3">Maps as objects</a></li>
</ul>
<p>These programs show how to read and write to a file using functions.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/2/4">Reading from a file (with CS poetry)</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/2/5">Writing to a file</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-1"><strong>Hands-On Practice</strong></h3>
<p><strong>Problem 1</strong></p>
<p>Write three mathematical functions:</p>
<ul>
<li><p><code>square</code> squares a passed in parameter</p>
</li>
<li><p><code>cube</code> cubes a passed in parameter</p>
</li>
<li><p><code>pow</code> raises a base number to an exponent</p>
</li>
</ul>
<p>For this group of functions, do not use any built-in mathematical functions.</p>
<p>Hint: look at the Clojure function <code>repeat</code> and <code>reduce</code> for the <code>pow</code> function. Use the <code>let</code> function to hold temporary values so that they can be referred to later.</p>
<p><strong>Problem 2</strong></p>
<p>Write a function that takes a number and will calculate the factorial value for that number.</p>
<pre><code class="lang-cpp"><span class="hljs-number">5</span>! is <span class="hljs-number">5</span> * <span class="hljs-number">4</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * <span class="hljs-number">1</span> = <span class="hljs-number">120</span>

<span class="hljs-number">10</span>! is <span class="hljs-number">10</span> * <span class="hljs-number">9</span> * <span class="hljs-number">8</span> * <span class="hljs-number">7</span> * <span class="hljs-number">6</span> * <span class="hljs-number">5</span> * <span class="hljs-number">4</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * <span class="hljs-number">1</span> = <span class="hljs-number">3</span>,<span class="hljs-number">628</span>,<span class="hljs-number">800</span>
</code></pre>
<p>Hint: this type of problem is typically done with recursion. But for now, try to do it without recursion. Look at the Clojure <code>range</code> and <code>reduce</code> functions.</p>
<p><strong>Problem 3</strong></p>
<p>Write a function that determines whether a number is prime or not. Use the <code>range</code> and <code>filter</code> functions to filter out non-primes in a range of values.</p>
<p>Hint: look at the <code>not-any?</code> and <code>mod</code> functions for determining whether a number is prime or not.</p>
<p><strong>Problem 4</strong></p>
<p>Write a function that takes one or more string parameters, converts them to numbers, and then adds them together and returns the sum.</p>
<pre><code class="lang-cpp">(println (add-strings <span class="hljs-string">"10"</span>)) ;prints <span class="hljs-number">10</span>

(println (add-strings <span class="hljs-string">"10"</span> <span class="hljs-string">"20"</span>)) ;prints <span class="hljs-number">30</span>

(println (add-strings <span class="hljs-string">"10"</span> <span class="hljs-string">"20"</span> <span class="hljs-string">"30"</span>)) ;prints <span class="hljs-number">60</span>

(println (add-strings <span class="hljs-string">"10"</span> <span class="hljs-string">"20"</span> <span class="hljs-string">"30"</span> <span class="hljs-string">"40"</span>)) ;prints <span class="hljs-number">100</span>
</code></pre>
<p>Use Clojure's <code>reduce</code> function or <code>apply</code> to turn the strings into numbers and then add them together.</p>
<h2 id="heading-closures"><strong>Closures</strong></h2>
<p>A closure is a way to associate data permanently with a function.</p>
<p>The first program shows how to bind data to a function.</p>
<ul>
<li><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/3/1">Closures</a></li>
</ul>
<p>The second program shows a more complex example of using closures.</p>
<ul>
<li><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/3/2">Interest in an account</a></li>
</ul>
<h3 id="heading-hands-on-practice-2"><strong>Hands-On Practice</strong></h3>
<p><strong>Problem 1</strong></p>
<p>Write a function that returns a function. The Fibonacci numbers are a sequence of numbers that are generated by summing the previous two numbers together:</p>
<pre><code class="lang-cpp"><span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span> <span class="hljs-number">5</span> <span class="hljs-number">8</span> <span class="hljs-number">13</span> <span class="hljs-number">21</span> <span class="hljs-number">34</span> ...
</code></pre>
<p>Usually, the first two numbers are assumed to be 0 and 1. But in this case, return a function that uses the specified first two numbers in the sequence. Then generate and print out the requested numbers in the sequence.</p>
<pre><code class="lang-cpp">(defn fibs-fn[firstFib secondFib] ...) ;;<span class="hljs-function">fill <span class="hljs-keyword">this</span> <span class="hljs-title">in</span>

<span class="hljs-params">(def another-fib (fibs-fn <span class="hljs-number">10</span> <span class="hljs-number">15</span>))</span> </span>;;create a fib function that prints starting with <span class="hljs-number">10</span> <span class="hljs-keyword">and</span> <span class="hljs-number">15</span>

(another-fib <span class="hljs-number">5</span>) ;;print first <span class="hljs-number">5</span> fibs: <span class="hljs-number">10</span> <span class="hljs-number">15</span> <span class="hljs-number">25</span> <span class="hljs-number">40</span> <span class="hljs-number">65</span>
</code></pre>
<h2 id="heading-recursion"><strong>Recursion</strong></h2>
<p>A recursive function is one that calls itself. Since every function call results in a stack frame being placed on the call stack, regular recursion runs the risk of 'blowing up the call stack'. Tail recursion, with <code>recur</code>, is an efficient way to simulate recursion without the downsides.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/4/1">Tail Recursion</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/4/2">Recursion and Fizz-Buzz</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/4/3">Recursion and Square Roots</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/4/4">Converting a String to an Integer in the Bases 2-16</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/4/5">Mortgage Scheduler</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-3"><strong>Hands-On Practice</strong></h3>
<p><strong>Problem 1</strong></p>
<p>Write a recursive function to reverse the letters of a string.</p>
<pre><code class="lang-cpp">(reverse-<span class="hljs-built_in">string</span> <span class="hljs-string">"Mark Mahoney"</span>) ;;returns <span class="hljs-string">"yenohaM kraM"</span>
</code></pre>
<p>You may need to create a recursive 'helper' function that takes a different number of parameters than the non-recursive function or use the <code>loop</code> form. Make sure you use recursion with the <code>recur</code> form so that you do not 'blow the stack'.</p>
<p><strong>Problem 2</strong></p>
<p>Write a function that will join a series of strings together separated by another string. The function should create and return a new string. Use recursion with <code>recur</code>.</p>
<pre><code class="lang-cpp">(defn join [separator &amp; parts]
   ;;your code here)

(join <span class="hljs-string">", "</span> <span class="hljs-string">"Mark"</span> <span class="hljs-string">"Laura"</span> <span class="hljs-string">"Buddy"</span> <span class="hljs-string">"Patrick"</span> <span class="hljs-string">"Willy"</span>) ;;<span class="hljs-string">"Mark, Laura, Buddy, Patrick, Willy"</span>
</code></pre>
<p><strong>Problem 3</strong></p>
<p>Write a function that takes in an integer and converts it to a string. The user can specify the base that the string is in from 2-10. The program should use recursion and <code>recur</code> (either a recursive function or the <code>loop</code> form).</p>
<pre><code class="lang-cpp">(to-<span class="hljs-built_in">string</span> <span class="hljs-number">100</span> <span class="hljs-number">10</span>) ;;<span class="hljs-string">"100"</span> decimal
(to-<span class="hljs-built_in">string</span> <span class="hljs-number">7</span> <span class="hljs-number">2</span>) ;;<span class="hljs-string">"111"</span> binary
</code></pre>
<h2 id="heading-lazy-sequences"><strong>Lazy Sequences</strong></h2>
<p>A lazy sequence defers the cost of creating values until they are needed. The first program shows how to create a lazy sequence. The next two are more concrete examples.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/5/1">Lazy sequences</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/5/2">Lazy Prime Generator (Fizz Buzz part 3)</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/5/3">Poker Probabilities</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-4"><strong>Hands-On Practice</strong></h3>
<p><strong>Problem 1</strong></p>
<p>Create a function that generates a lazy sequence of squares. For example, (1 4 9 16 ... to infinity). Use it to print the first 10 squared values.</p>
<p>Then write a function that generates a lazy sequence of values raised to a power:</p>
<pre><code class="lang-cpp">(defn lazy-<span class="hljs-built_in">pow</span> [start-val power]
  ...)

(take <span class="hljs-number">6</span> (lazy-<span class="hljs-built_in">pow</span> <span class="hljs-number">10</span> <span class="hljs-number">2</span>)) ;(<span class="hljs-number">100</span> <span class="hljs-number">121</span> <span class="hljs-number">144</span> <span class="hljs-number">169</span> <span class="hljs-number">196</span> <span class="hljs-number">225</span>)
(take <span class="hljs-number">6</span> (lazy-<span class="hljs-built_in">pow</span> <span class="hljs-number">10</span> <span class="hljs-number">3</span>)) ;(<span class="hljs-number">1000</span> <span class="hljs-number">1331</span> <span class="hljs-number">1728</span> <span class="hljs-number">2197</span> <span class="hljs-number">2744</span> <span class="hljs-number">3375</span>)
</code></pre>
<p><strong>Problem 2</strong></p>
<p>Write a function that generates an infinite lazy sequence of possible permutations of the passed in sequence.</p>
<pre><code class="lang-cpp">(take <span class="hljs-number">3</span> (lazy-perm [<span class="hljs-string">"a"</span> <span class="hljs-string">"b"</span> <span class="hljs-string">"c"</span>]))
;(<span class="hljs-string">"a"</span> <span class="hljs-string">"b"</span> <span class="hljs-string">"c"</span>)

(take <span class="hljs-number">12</span> (lazy-perm [<span class="hljs-string">"a"</span> <span class="hljs-string">"b"</span> <span class="hljs-string">"c"</span>])) 
;(<span class="hljs-string">"a"</span> <span class="hljs-string">"b"</span> <span class="hljs-string">"c"</span> <span class="hljs-string">"aa"</span> <span class="hljs-string">"ab"</span> <span class="hljs-string">"ac"</span> <span class="hljs-string">"ba"</span> <span class="hljs-string">"bb"</span> <span class="hljs-string">"bc"</span> <span class="hljs-string">"ca"</span> <span class="hljs-string">"cb"</span> <span class="hljs-string">"cc"</span>)

(take <span class="hljs-number">39</span> (lazy-perm [<span class="hljs-string">"a"</span> <span class="hljs-string">"b"</span> <span class="hljs-string">"c"</span>])) 
;(<span class="hljs-string">"a"</span> <span class="hljs-string">"b"</span> <span class="hljs-string">"c"</span> <span class="hljs-string">"aa"</span> <span class="hljs-string">"ab"</span> <span class="hljs-string">"ac"</span> <span class="hljs-string">"ba"</span> <span class="hljs-string">"bb"</span> <span class="hljs-string">"bc"</span> <span class="hljs-string">"ca"</span> <span class="hljs-string">"cb"</span> <span class="hljs-string">"cc"</span> <span class="hljs-string">"aaa"</span> <span class="hljs-string">"aab"</span> <span class="hljs-string">"aac"</span> <span class="hljs-string">"aba"</span> <span class="hljs-string">"abb"</span> <span class="hljs-string">"abc"</span> <span class="hljs-string">"aca"</span> <span class="hljs-string">"acb"</span> <span class="hljs-string">"acc"</span> <span class="hljs-string">"baa"</span> <span class="hljs-string">"bab"</span> <span class="hljs-string">"bac"</span> <span class="hljs-string">"bba"</span> <span class="hljs-string">"bbb"</span> <span class="hljs-string">"bbc"</span> <span class="hljs-string">"bca"</span> <span class="hljs-string">"bcb"</span> <span class="hljs-string">"bcc"</span> <span class="hljs-string">"caa"</span> <span class="hljs-string">"cab"</span> <span class="hljs-string">"cac"</span> <span class="hljs-string">"cba"</span> <span class="hljs-string">"cbb"</span> <span class="hljs-string">"cbc"</span> <span class="hljs-string">"cca"</span> <span class="hljs-string">"ccb"</span> <span class="hljs-string">"ccc"</span>)

(take <span class="hljs-number">120</span> (lazy-perm [<span class="hljs-string">"a"</span> <span class="hljs-string">"b"</span> <span class="hljs-string">"c"</span>]))
;(<span class="hljs-string">"a"</span> <span class="hljs-string">"b"</span> <span class="hljs-string">"c"</span> <span class="hljs-string">"aa"</span> <span class="hljs-string">"ab"</span> <span class="hljs-string">"ac"</span> <span class="hljs-string">"ba"</span> <span class="hljs-string">"bb"</span> <span class="hljs-string">"bc"</span> <span class="hljs-string">"ca"</span> <span class="hljs-string">"cb"</span> <span class="hljs-string">"cc"</span> <span class="hljs-string">"aaa"</span> <span class="hljs-string">"aab"</span> <span class="hljs-string">"aac"</span> <span class="hljs-string">"aba"</span> <span class="hljs-string">"abb"</span> <span class="hljs-string">"abc"</span> <span class="hljs-string">"aca"</span> <span class="hljs-string">"acb"</span> <span class="hljs-string">"acc"</span> <span class="hljs-string">"baa"</span> <span class="hljs-string">"bab"</span> <span class="hljs-string">"bac"</span> <span class="hljs-string">"bba"</span> <span class="hljs-string">"bbb"</span> <span class="hljs-string">"bbc"</span> <span class="hljs-string">"bca"</span> <span class="hljs-string">"bcb"</span> <span class="hljs-string">"bcc"</span> <span class="hljs-string">"caa"</span> <span class="hljs-string">"cab"</span> <span class="hljs-string">"cac"</span> <span class="hljs-string">"cba"</span> <span class="hljs-string">"cbb"</span> <span class="hljs-string">"cbc"</span> <span class="hljs-string">"cca"</span> <span class="hljs-string">"ccb"</span> <span class="hljs-string">"ccc"</span> <span class="hljs-string">"aaaa"</span> <span class="hljs-string">"aaab"</span> <span class="hljs-string">"aaac"</span> <span class="hljs-string">"aaba"</span> <span class="hljs-string">"aabb"</span> <span class="hljs-string">"aabc"</span> <span class="hljs-string">"aaca"</span> <span class="hljs-string">"aacb"</span> <span class="hljs-string">"aacc"</span> <span class="hljs-string">"abaa"</span> <span class="hljs-string">"abab"</span> <span class="hljs-string">"abac"</span> <span class="hljs-string">"abba"</span> <span class="hljs-string">"abbb"</span> <span class="hljs-string">"abbc"</span> <span class="hljs-string">"abca"</span> <span class="hljs-string">"abcb"</span> <span class="hljs-string">"abcc"</span> <span class="hljs-string">"acaa"</span> <span class="hljs-string">"acab"</span> <span class="hljs-string">"acac"</span> <span class="hljs-string">"acba"</span> <span class="hljs-string">"acbb"</span> <span class="hljs-string">"acbc"</span> <span class="hljs-string">"acca"</span> <span class="hljs-string">"accb"</span> <span class="hljs-string">"accc"</span> <span class="hljs-string">"baaa"</span> <span class="hljs-string">"baab"</span> <span class="hljs-string">"baac"</span> <span class="hljs-string">"baba"</span> <span class="hljs-string">"babb"</span> <span class="hljs-string">"babc"</span> <span class="hljs-string">"baca"</span> <span class="hljs-string">"bacb"</span> <span class="hljs-string">"bacc"</span> <span class="hljs-string">"bbaa"</span> <span class="hljs-string">"bbab"</span> <span class="hljs-string">"bbac"</span> <span class="hljs-string">"bbba"</span> <span class="hljs-string">"bbbb"</span> <span class="hljs-string">"bbbc"</span> <span class="hljs-string">"bbca"</span> <span class="hljs-string">"bbcb"</span> <span class="hljs-string">"bbcc"</span> <span class="hljs-string">"bcaa"</span> <span class="hljs-string">"bcab"</span> <span class="hljs-string">"bcac"</span> <span class="hljs-string">"bcba"</span> <span class="hljs-string">"bcbb"</span> <span class="hljs-string">"bcbc"</span> <span class="hljs-string">"bcca"</span> <span class="hljs-string">"bccb"</span> <span class="hljs-string">"bccc"</span> <span class="hljs-string">"caaa"</span> <span class="hljs-string">"caab"</span> <span class="hljs-string">"caac"</span> <span class="hljs-string">"caba"</span> <span class="hljs-string">"cabb"</span> <span class="hljs-string">"cabc"</span> <span class="hljs-string">"caca"</span> <span class="hljs-string">"cacb"</span> <span class="hljs-string">"cacc"</span> <span class="hljs-string">"cbaa"</span> <span class="hljs-string">"cbab"</span> <span class="hljs-string">"cbac"</span> <span class="hljs-string">"cbba"</span> <span class="hljs-string">"cbbb"</span> <span class="hljs-string">"cbbc"</span> <span class="hljs-string">"cbca"</span> <span class="hljs-string">"cbcb"</span> <span class="hljs-string">"cbcc"</span> <span class="hljs-string">"ccaa"</span> <span class="hljs-string">"ccab"</span> <span class="hljs-string">"ccac"</span> <span class="hljs-string">"ccba"</span> <span class="hljs-string">"ccbb"</span> <span class="hljs-string">"ccbc"</span> <span class="hljs-string">"ccca"</span> <span class="hljs-string">"cccb"</span> <span class="hljs-string">"cccc"</span>)
</code></pre>
<h2 id="heading-macros"><strong>Macros</strong></h2>
<p>A macro specifies some code to be executed, sort of like a function, but it also allows some of that code to be replaced with values that come from the user.</p>
<p>The code in a macro is kind of like a template that can be altered to suit the caller’s needs. With this powerful feature, the language can be expanded to do things that the language inventor never thought to add.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/6/1">Macros</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/6/2">Set macros</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-5"><strong>Hands-On Practice</strong></h3>
<p><strong>Problem 1</strong></p>
<p>Write a macro that takes in a grade earned on a student assignment (on a 0-100 scale) and some code to execute if the grade is a passing or failing.</p>
<pre><code class="lang-cpp">(defmacro eval-grade [grade <span class="hljs-keyword">if</span>-passing <span class="hljs-keyword">if</span>-failing] ...)
</code></pre>
<p>And use it to print or call a function based on the value of the grade</p>
<pre><code class="lang-cpp">(def users-grade <span class="hljs-number">43</span>)

(eval-grade users-grade (println <span class="hljs-string">"Passing"</span>) (println <span class="hljs-string">"Failing"</span>)) ;;<span class="hljs-string">"Failing"</span>

(eval-grade users-grade (praise users-grade) (warning users-grade)) ;;call the warning function
</code></pre>
<h2 id="heading-concurrency"><strong>Concurrency</strong></h2>
<p>Concurrency in Clojure is a big topic. I start by discussing threads. Then I talk about different strategies for dealing with data that is shared among different threads.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/7/1">Threads</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/7/2">Threaded poker</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/7/3">refs and threads</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/7/4">Atoms</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/7/5">Poker with atoms</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/7/6">Thread logging with agents</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook/chapter/7/7">Simpler concurrency</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-6"><strong>Hands-On Practice</strong></h3>
<p><strong>Problem 1</strong></p>
<p>This lab asks you to create a Clojure program that will count how many primes are in a given range.</p>
<p>Create a thread pool and have each thread check a single number in the range. If it finds a prime, it will increase a counter (which should be an <code>atom</code> since it is shared by all of the threads). Look at the program above on Atoms as a starting point.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you've made it this far, you’ve already taken meaningful steps toward learning a language that can change how you write and think about code.</p>
<p>Clojure offers a fresh perspective on programming, one that focuses on simplicity, immutability, and the power of functions. Learning Clojure will change your brain and you will take these lessons with you to other languages as well.</p>
<p>So keep experimenting, keep asking questions, and keep practicing to sharpen your skills.</p>
<h2 id="heading-comments-and-feedback"><strong>Comments and Feedback</strong></h2>
<p>You can find all of these code playbacks in the free 'book', <a target="_blank" href="https://playbackpress.com/books/cljbook/">An Animated Introduction to Clojure</a>. There are more free books here:</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/">An Animated Introduction to Programming in C++</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/pybook">An Animated Introduction to Programming with Python</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlbook">Database Design and SQL for Beginners</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/workedsqlbook">Worked SQL Examples</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook">Programming with SQLite</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/webdevbook">An Introduction to Web Development from Back to Front</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook">An Animated Introduction to Clojure</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook">An Animated Introduction to Elixir</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook">A Brief Introduction to Ruby</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/flutterbook">Mobile App Development with Dart and Flutter</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/patternsbook">OO Design Patterns with Java</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/wordzearchbook">How I Built It: Word Zearch</a></p>
</li>
</ul>
<p>Comments and feedback are welcome via email: <a target="_blank" href="mailto:mark@playbackpress.com">mark@playbackpress.com</a>.</p>
<p>If you'd like to support my work and help keep Playback Press free for all, consider donating using <a target="_blank" href="https://github.com/sponsors/markm208">GitHub Sponsors</a>. I use all of the donations for hosting costs. Your support helps me continue creating educational content like this. Thank you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Functional Programming in Java ]]>
                </title>
                <description>
                    <![CDATA[ Functional programming (FP) is a programming paradigm. It emphasizes the use of pure functions that don't have side effects and always return the same output for a given input. This article explores how to implement FP concepts in Java, including vie... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/functional-programming-in-java/</link>
                <guid isPermaLink="false">66d460ee868774922c88500e</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sameer Shukla ]]>
                </dc:creator>
                <pubDate>Tue, 14 Mar 2023 17:34:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/lambda.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Functional programming (FP) is a programming paradigm. It emphasizes the use of pure functions that don't have side effects and always return the same output for a given input.</p>
<p>This article explores how to implement FP concepts in Java, including viewing functions as first-class citizens, chaining, and composing them to create function pipelines.</p>
<p>We'll also discuss the technique of currying, which allows a function that takes multiple arguments to be transformed into a chain of functions that each take a single argument. This can simplify the use of complex functions and make them more reusable.</p>
<p>In this article, I'll show you examples of how to implement these concepts in Java using modern language features, like “java.util.function.Function”, “java.util.function.BiFunction”, and a user-defined TriFunction. We'll then see how to overcome its limitation using currying.</p>
<h2 id="heading-the-javautilfunctionfunction-interface">The <code>java.util.function.Function</code> interface</h2>
<p>The java.util.function.Function interface is a key component of the Java 8 functional programming API. The java.util.function.Function is a functional interface in Java that takes input of type 'T' and produces an output of type 'R'.</p>
<p>In functional programming, functions are first-class citizens, meaning that they can be passed around as values, stored in variables or data structures, and used as arguments or return values of other functions.</p>
<p>The function interface provides a way to define and manipulate functions in Java code.</p>
<p>The function interface represents a function that takes one input and produces one output. It has a single abstract method, <code>apply()</code>, which takes an argument of a specified type and returns a result of a specified type.</p>
<p>You can use the function interface to define new functions, as well as to manipulate and compose existing functions. For example, you can use it to convert a list of objects of one type to a list of objects of another type, or to apply a series of transformations to a stream of data.</p>
<p>One of the main benefits of the function interface is that it allows you to write code that is more concise and expressive. By defining functions as values and passing them around as arguments or return values, developers can create more modular and reusable code. Also, by using lambdas to define functions, Java code can be more expressive and easier to read.</p>
<p>You can think about <code>java.util.function.Function</code> like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-98.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Function&lt;A, B&gt;</em></p>
<p>The java.util.function.BiFunction is also a functional interface in Java that takes two inputs 'T' and 'U' and produces an output of type 'R'. In short, BiFunction takes 2 inputs and returns an output:</p>
<pre><code class="lang-bash">BiFunction&lt;Integer, Integer, Integer&gt; sum = (a, b) -&gt; a + b;
</code></pre>
<p>You can think about <code>java.util.function.BiFunction</code> like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-99.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>BiFunction&lt;A, B, C&gt;</em></p>
<h2 id="heading-function-composition-and-chaining">Function Composition and Chaining</h2>
<p>Function chaining is a technique in functional programming that involves composing multiple functions into a single pipeline or chain.</p>
<p>In Java FP, function chaining is often used to transform data in a series of steps, where each step applies a specific transformation to the data and passes it on to the next step in the chain.</p>
<p>The function interface in Java provides a powerful tool for function chaining. Each function in the chain is defined as a separate instance of the Function interface. The output of each function becomes the input to the next function in the chain. This allows for a series of transformations to be applied to the data, one after another, until the final result is produced.</p>
<h3 id="heading-how-to-use-the-andthen-method">How to use the <code>andThen</code> method</h3>
<p>The "andThen()" method is a default method provided by the function interface in Java. This method takes a sequence of two functions and applies them in succession, using the output of the first function as the input to the second function. This chaining of the functions results in a new function that combines the behavior of both functions in a single transformation.</p>
<p>The syntax of <code>andThen</code> looks like this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">default</span> &lt;V&gt; <span class="hljs-function">Function&lt;T, V&gt; <span class="hljs-title">andThen</span><span class="hljs-params">(Function&lt;? <span class="hljs-keyword">super</span> R, ? extends V&gt; after)</span></span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-107.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>andThen</em></p>
<p>We can break the example down into series of steps. Initially the "multiply" function will be executed and its output passed as input to the "add" function. Then the "logOutput" function is used to log the resulting output.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FunctionChainingExample</span> </span>{

    <span class="hljs-keyword">static</span> Logger logger = Logger.getLogger(FunctionChainingExample.class.getName());

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Function&lt;Integer, Integer&gt; multiply = x -&gt; x * <span class="hljs-number">2</span>;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Function&lt;Integer, Integer&gt; add = x -&gt; x + <span class="hljs-number">2</span>;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Function&lt;Integer, Unit&gt; logOutput = x -&gt; {
        logger.info(<span class="hljs-string">"Data:"</span> + x);
        <span class="hljs-keyword">return</span> Unit.unit();
    };

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Unit <span class="hljs-title">execute</span><span class="hljs-params">(Integer input)</span> </span>{
        Function&lt;Integer, Unit&gt; pipeline = multiply
                                               .andThen(add)
                                               .andThen(logOutput);
        <span class="hljs-keyword">return</span> pipeline.apply(input);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        execute(<span class="hljs-number">10</span>);
    }

}
</code></pre>
<p>The the above code snippet showcases the creation of three functions, namely multiply, add, and logOutput.</p>
<p>The function <code>multiply</code> accepts an integer input and produces an integer output, just like the <code>add</code> function. But, the <code>logOutput</code> function accepts an integer input and returns nothing (as represented by the Unit object, which implies the absence of a value).</p>
<p>The <code>execute</code> function chains the three functions together, where the output of multiply is utilized as the input for the add function, and the resulting output of add is passed to the logOutput function for logging purposes. The above example showcases function chaining using the <code>andThen</code> default method.</p>
<h3 id="heading-how-to-use-the-compose-method">How to use the <code>compose</code> method</h3>
<p>Unlike the <code>andThen</code> method, the <code>compose</code> method is another default method provided by the function interface in Java. It applies the first function to the output of the second function.</p>
<p>This means that the second function is applied to the input first, and then the first function is applied to the output of the second function. As a result, a chain of functions is created where the output of the second function becomes the input of the first function.</p>
<p>The compose function looks like this:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">default</span>  Function&lt;V, R&gt; <span class="hljs-title">compose</span><span class="hljs-params">(Function&lt;? <span class="hljs-keyword">super</span> V, ? extends T&gt; before)</span></span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-118.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>compose</em></p>
<p>When to use <code>andThen</code> vs <code>compose</code> depends on the order in which you want the functions to be applied.</p>
<p>If you want to apply the functions in the order they are defined, from left to right, then you should use the <code>andThen</code> method. This method applies the first function to the input, and then applies the second function to the output of the first function.</p>
<p>This is useful when you want to chain together functions that process the input data in a specific order.</p>
<p>On the other hand, if you want to apply the functions in the opposite order, from right to left, then you should use the <code>compose</code> method. This method applies the second function to the input, and then applies the first function to the output of the second function.</p>
<p>This is useful when you want to chain together functions that need to be applied in the opposite order of the way they are defined.</p>
<p>In general, you should use <code>andThen</code> when you want to apply the functions in the order they are defined, and use <code>compose</code> when you want to apply the functions in the opposite order. But the choice between the two methods ultimately depends on the specific requirements of your use case.</p>
<pre><code class="lang-bash"> public static Unit compose(Integer input) {
        Function&lt;Integer, Unit&gt; pipeline = logOutput
                                            .compose(add)
                                            .compose(multiply);
        <span class="hljs-built_in">return</span> pipeline.apply(input);
    }
</code></pre>
<p>In the <code>compose</code> example, the functions are executed in a right-to-left order. Firstly, <code>multiply</code> is executed and its output is passed to the <code>add</code> function. Then, the resulting output of the <code>add</code> function is passed to <code>logOutput</code> for logging purposes.</p>
<h3 id="heading-how-to-use-the-apply-function">How to use the <code>apply()</code> function</h3>
<p>The <code>apply()</code> method takes an input and returns a result. It is used to apply a function to an argument and compute a result.</p>
<p>The <code>apply()</code> function is a method of functional interfaces, such as the function interface, that takes an argument of a specified type and returns a result of a specified type. It is the single abstract method of these interfaces, which is required for them to be used as functional interfaces.</p>
<p>The <code>apply()</code> function defines the behavior of the functional interface. When an instance of a functional interface is created, the <code>apply()</code> function is implemented to define what the functional interface does when it is called with an argument.</p>
<pre><code class="lang-bash">Function&lt;Integer, Integer&gt; multiply = x -&gt; x * x;
        int result = multiply.apply(5);
</code></pre>
<p>In this code, we define a function called <code>multiply</code> that takes an integer argument and returns the square of that integer. We then call the <code>apply()</code> function on this function, passing in the integer value of 5. The <code>apply()</code> function executes the lambda expression defined in the <code>square</code> Function, and returns the result of the computation, which in this case is 25.</p>
<p>Let's understand by looking at a real-world example, FileReaderPipeline.</p>
<pre><code class="lang-bash">public class FileReaderPipeline {

    static Function&lt;String, String&gt; trim = String::trim;
    static Function&lt;String, String&gt; toUpperCase = String::toUpperCase;
    static Function&lt;String, String&gt; replaceSpecialCharacters = 
        str -&gt; str.replaceAll(<span class="hljs-string">"[^\\p{Alpha}]+"</span>, <span class="hljs-string">""</span>);

    static Function&lt;String, String&gt; pipeline = 
                                trim
                                  .andThen(toUpperCase)
                                  .andThen(replaceSpecialCharacters);

 public static void main(String[] args) throws IOException {
        try (BufferedReader reader = new BufferedReader(new     FileReader(<span class="hljs-string">"example.txt"</span>))) {
            String line;
            <span class="hljs-keyword">while</span> ((line = reader.readLine()) != null) {
                String result = pipeline.apply(line);
                System.out.println(result);
            }
        }
    }
}
</code></pre>
<p>The above code defines a FileReaderPipeline class, which reads lines from a file, processes them through a pipeline of functions, and prints the resulting output.</p>
<p>First, three functions <code>trim</code>, <code>toUpperCase</code>, and <code>replaceSpecialCharacters</code> are defined using method references and lambda expressions. <code>trim</code> removes leading and trailing whitespace from a String, <code>toUpperCase</code> converts the string to uppercase, and <code>replaceSpecialCharacters</code> removes any non-alphabetic characters from the string.</p>
<p>Next, a function pipeline is created using the <code>andThen</code> method, which chains the three functions together. The input to the pipeline function is a String, and the output is also a String. When a String is passed to the pipeline function, it first removes any leading or trailing whitespace, then converts the string to uppercase, and finally removes any non-alphabetic characters.</p>
<p>Finally, in the <code>main</code> method, the program reads lines from a file (in this example, "example.txt") using a <code>BufferedReader</code>. Each line is processed through the pipeline function using the <code>apply</code> method, which applies each function in the pipeline in sequence, and returns the resulting output. The resulting output is then printed to the console using <code>System.out.println</code>.</p>
<h2 id="heading-function-currying">Function Currying</h2>
<p>The Java util package contains two functional interfaces known as "Function&lt;A, B&gt;" and "BiFunction&lt;A, B, C&gt;". The <code>Function</code> interface takes a single input and produces an output, whereas the <code>BiFunction</code> interface takes two inputs and produces an output. Here is an illustration:</p>
<pre><code class="lang-bash"> Function&lt;String, String&gt; toUpper = str -&gt; str.toUpperCase();
 BiFunction&lt;Integer, Integer, Integer&gt; sum = (a, b) -&gt; a + b;
</code></pre>
<p>This is a clear constraint as there are only two functions, with one accepting a single input and the other accepting two inputs. Consequently, if we need a function that takes three inputs, we must construct our own customized function.</p>
<p>To this end, let's design a function that accepts three inputs and name it <code>TriFunction</code>. Here is an example implementation:</p>
<pre><code class="lang-bash">@FunctionalInterface
public interface TriFunction&lt;A, B, C, O&gt; {
    O apply(A a, B b, C c);

    default &lt;R&gt; TriFunction&lt;A, B, C, O&gt; andThen(TriFunction&lt;A, B, C, O&gt; after) {
        <span class="hljs-built_in">return</span> (A a, B b, C c) -&gt; after.apply(a,b,c);
    }
}
</code></pre>
<pre><code class="lang-bash">TriFunction&lt;Integer, Integer, Integer, Integer&gt; sum = (a, b, c) -&gt; a + b + c;                                                                
int result = sum.apply(1, 2, 3);
</code></pre>
<p>In situations where we require more parameters than what the available functions can accept, we can leverage currying to overcome this limitation.</p>
<p>We can refactor the previous function using currying, which involves decomposing a function that takes multiple arguments into a sequence of functions, each of which accepts only one argument. This is in line with the definition of currying, which is a technique employed in Functional Programming.</p>
<pre><code class="lang-bash">Function&lt;Integer, Function&lt;Integer, Function&lt;Integer, Integer&gt;&gt;&gt;     sumWithThreeParams = (a) -&gt; (b) -&gt; (c) -&gt; a + b + c;
                                                                       Function&lt;Integer, Function&lt;Integer, Function&lt;Integer, Function&lt;Integer, Integer&gt;&gt;&gt;&gt; sumWithFourParams = (a)-&gt;(b)-&gt;(c)-&gt;(d) -&gt; a + b + c + d;
</code></pre>
<p>The above declares a new <code>Function</code> named <code>sumWithThreeParams</code> that takes an <code>Integer</code> input. It returns a new <code>Function</code> that takes an <code>Integer</code> input and returns yet another new <code>Function</code> that takes an <code>Integer</code> input and returns an <code>Integer</code> output. Similarly a new Function named <code>sumWithFourParams</code> is created.</p>
<p>Note that the curried function <code>sumWithThreeParams</code> and <code>sumWithFourParams</code> allows us to partially apply arguments to the function, which can be useful in situations where we have some of the inputs available but not all of them</p>
<pre><code class="lang-bash">Function&lt;Integer, Function&lt;Integer, Integer&gt;&gt; partialSumWithTwoParams                                     = sumWithThreeParams.apply(5);
                                                                        Function&lt;Integer, Integer&gt; partialSumWithOneParams 
                                 = partialSumWithTwoParams.apply(10);

                                                                        int c = 15;
int result = partialSumWithOneParams.apply(c);
System.out.println(result); //30
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we covered the implementation of functional programming (FP) concepts in Java, such as treating functions as first-class citizens, composing them into pipelines, and utilizing currying to simplify complex functions.</p>
<p>We have provided examples using modern language features like <code>java.util.function.Function</code> and <code>java.util.function.BiFunction</code>, as well as a user-defined <code>TriFunction</code> with currying to overcome its limitations.</p>
<p>By applying these techniques, developers can write more concise, reusable, and maintainable code in Java.</p>
<p>With the growing popularity of FP in the industry, understanding and implementing these concepts is becoming increasingly important for Java developers.</p>
<p>After reading this article, if you have found it useful and would like to explore more practical examples, <a target="_blank" href="https://github.com/sameershukla/JavaFPLearning">please visit the repository</a> and consider giving it a star.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Functions Tutorial – IIFE, Function Parameters, and Code Blocks Explained ]]>
                </title>
                <description>
                    <![CDATA[ Functions are one of the most widely-used features in programming. So, it helps to have a solid understanding of how they work. This tutorial discusses everything you need to know to use JavaScript functions like a pro. Table of Contents What Is a F... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-function-iife-parameters-code-blocks-explained/</link>
                <guid isPermaLink="false">66ba0df8d14c87384322b680</guid>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Wed, 05 Oct 2022 16:06:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/programming-image-by-mohamed-hassan-from-pixabay-javascript-function-iffe-parameters-blocks-explained-codesweetly.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Functions are one of the most widely-used features in programming. So, it helps to have a solid understanding of how they work.</p>
<p>This tutorial discusses everything you need to know to use JavaScript functions like a pro.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-a-function">What Is a Function?</a></li>
<li><a class="post-section-overview" href="#heading-why-functions">Why Functions?</a></li>
<li><a class="post-section-overview" href="#heading-syntax-of-a-javascript-function-1">Syntax of a JavaScript Function</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-function-keyword">What Is a <code>function</code> Keyword?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-function-name">What Is a Function Name?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-parameter">What Is a Parameter?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-code-block">What Is a Code Block?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-function-body">What Is a Function Body?</a></li>
<li><a class="post-section-overview" href="#heading-types-of-javascript-functions">Types of JavaScript Functions</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-function-declaration">What Is a JavaScript Function Declaration?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-function-expression">What Is a JavaScript Function Expression?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-arrow-function-expression">What Is a JavaScript Arrow Function Expression?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-immediately-invoked-function-expression">What Is a JavaScript Immediately Invoked Function Expression?</a></li>
<li><a class="post-section-overview" href="#heading-overview">Overview</a></li>
</ol>
<p>So, let's get started from the basics.</p>
<h2 id="heading-what-is-a-function">What Is a Function?</h2>
<p>A <strong>JavaScript function</strong> is an executable piece of code developers use to bundle a block of zero or more statements.</p>
<p>In other words, a function is an executable subprogram (mini-program).</p>
<p>A JavaScript function is a subprogram because its body consists of a series of statements (instructions) to computers—just like a regular program.</p>
<p>The instructions in a function's body can be a <a target="_blank" href="https://codesweetly.com/javascript-variable#example-3-javascript-variable">variable</a> declaration, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return">return</a> call, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/console/log">console.log()</a> invocation, <a class="post-section-overview" href="#heading-syntax-of-a-javascript-function-1">function</a> definition, or any other JavaScript <a target="_blank" href="https://codesweetly.com/javascript-statement">statements</a>.</p>
<p><strong>Note:</strong></p>
<ul>
<li>A program is a list of instructions written for computers to execute.</li>
<li>Unlike other <a target="_blank" href="https://codesweetly.com/javascript-non-primitive-data-type#types-of-javascript-objects">object types</a>, you can invoke a function without storing it in a variable.</li>
<li>A JavaScript function is similar to other programming languages' procedures or subroutines.</li>
</ul>
<h2 id="heading-why-functions">Why Functions?</h2>
<p>Functions provide a way to bundle pieces of code together and reuse them anytime, anywhere, for an unlimited period. This helps you eliminate the burden of writing the same set of code repeatedly.</p>
<p>For instance, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/alert">alert()</a> is a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window">built-in window function</a> that someone wrote once for all developers to use anytime, anywhere.</p>
<h2 id="heading-syntax-of-a-javascript-function">Syntax of a JavaScript Function</h2>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nameOfFunction</span>(<span class="hljs-params">parameter1, parameter2, ..., parameterX</span>) </span>{
  <span class="hljs-comment">// function's body</span>
}
</code></pre>
<p>A function is composed of five elements:</p>
<ol>
<li>A <code>function</code> keyword</li>
<li>The function's name</li>
<li>A list of zero or more parameters</li>
<li>A code block (<code>{...}</code>)</li>
<li>The function's body</li>
</ol>
<p>Let's discuss each element.</p>
<h2 id="heading-what-is-a-function-keyword">What Is a <code>function</code> Keyword?</h2>
<p>We use the <code>function</code> keyword to declare to browsers that a specific piece of code is a JavaScript function—not a mathematical or other generic function.</p>
<h2 id="heading-what-is-a-function-name">What Is a Function Name?</h2>
<p>A <strong>function's name</strong> allows you to create an identifier for your function, which you can use to reference it.</p>
<h2 id="heading-what-is-a-parameter">What Is a Parameter?</h2>
<p>A <strong>parameter</strong> specifies the name you wish to call your function's <a target="_blank" href="https://codesweetly.com/javascript-arguments">argument</a>.</p>
<p>A parameter is an optional component of a function. In other words, you do not need to specify a parameter if your function does not accept any argument.</p>
<p>For instance, JavaScript's <a target="_blank" href="https://codesweetly.com/javascript-pop-method">pop()</a> method is a function without any parameter because it does not accept arguments.</p>
<p>On the other hand, <a target="_blank" href="https://codesweetly.com/javascript-foreach-method">forEach()</a> has two parameters that accept two arguments.</p>
<h3 id="heading-example-of-a-javascript-parameter">Example of a JavaScript parameter</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My full name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>);
}

<span class="hljs-comment">// Invoke myName function while passing two arguments to its parameters:</span>
myName(<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My full name is Oluwatobi Sofela."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-edvj3g?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The <code>myName()</code> function in the snippet above has two parameters: <code>firstName</code> and <code>lastName</code>.</p>
<p>Suppose you wish to pre-define values for your parameters that browsers can use if users do not invoke the function with the required arguments. In that case, you can create default parameters.</p>
<h3 id="heading-what-is-a-default-parameter">What is a default parameter?</h3>
<p><strong>Default parameters</strong> allow you to initialize your function's parameters with default values.</p>
<p>For instance, suppose users invoke your function without providing a required argument. In such a case, browsers will set the parameter's value to <code>undefined</code>.</p>
<p>However, default parameters allow you to define the values browsers should use instead of <code>undefined</code>.</p>
<h3 id="heading-examples-of-default-parameters">Examples of default parameters</h3>
<p>Below are examples of how default parameters work in JavaScript.</p>
<h4 id="heading-how-to-define-a-function-with-no-default-parameters">How to define a function with no default parameters</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My full name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>);
}

<span class="hljs-comment">// Invoke myName function while passing one argument to its parameters:</span>
myName(<span class="hljs-string">"Oluwatobi"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My full name is Oluwatobi undefined."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-9ce3xt?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The computer automatically set the <code>lastName</code> parameter to <code>undefined</code> because we did not provide a default value.</p>
<h4 id="heading-how-to-define-a-function-with-an-undefined-argument-and-no-default-parameter">How to define a function with an <code>undefined</code> argument and no default parameter</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My full name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>);
}

<span class="hljs-comment">// Invoke myName function while passing two arguments to its parameters:</span>
myName(<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-literal">undefined</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My full name is Oluwatobi undefined."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-csbxta?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The computer set the <code>lastName</code> parameter to <code>undefined</code> because we provided <code>undefined</code> as <code>myName()</code>'s second argument.</p>
<h4 id="heading-how-to-define-a-function-with-a-default-parameter">How to define a function with a default parameter</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">firstName, lastName = <span class="hljs-string">"Sofela"</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My full name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>);
}

<span class="hljs-comment">// Invoke myName function while passing one argument to its parameters:</span>
myName(<span class="hljs-string">"Oluwatobi"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My full name is Oluwatobi Sofela."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ghiyzm?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Instead of <code>undefined</code>, JavaScript used <code>"Sofela"</code> as the <code>lastName</code> parameter's default argument.</p>
<h4 id="heading-how-to-define-a-function-with-an-undefined-argument-and-a-default-parameter">How to define a function with an <code>undefined</code> argument and a default parameter</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">firstName, lastName = <span class="hljs-string">"Sofela"</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My full name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>);
}

<span class="hljs-comment">// Invoke myName function while passing two arguments to its parameters:</span>
myName(<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-literal">undefined</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My full name is Oluwatobi Sofela."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-umqgqp?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Instead of <code>undefined</code>, JavaScript used <code>"Sofela"</code> as the <code>lastName</code> parameter's default argument.</p>
<p>Let's now discuss the fourth element of a JavaScript function: a <strong>code block.</strong></p>
<h2 id="heading-what-is-a-code-block">What Is a Code Block?</h2>
<p>A <strong>block</strong> is a pair of braces (<code>{...}</code>) used to group multiple statements together.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js">{
  <span class="hljs-keyword">const</span> hourNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
}
</code></pre>
<p>The block in the snippet above encased one JavaScript <a target="_blank" href="https://codesweetly.com/javascript-statement">statement</a>.</p>
<p><strong>Here's another example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours() &lt; <span class="hljs-number">18</span>) {
  <span class="hljs-keyword">const</span> hourNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
  <span class="hljs-keyword">const</span> minutesNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The time is <span class="hljs-subst">${hourNow}</span>:<span class="hljs-subst">${minutesNow}</span>.`</span>);
}
</code></pre>
<p>The <code>if</code> condition's code block grouped three JavaScript statements together.</p>
<p><strong>Now, consider this snippet:</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getTime</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> hourNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
  <span class="hljs-keyword">const</span> minutesNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The time is <span class="hljs-subst">${hourNow}</span>:<span class="hljs-subst">${minutesNow}</span>.`</span>);
}
</code></pre>
<p>The <code>getTime()</code> function's code block grouped three JavaScript statements. Note that the "function body" is the space inside the function's code block. Let's talk more about it now.</p>
<h2 id="heading-what-is-a-function-body">What Is a Function Body?</h2>
<p>A <strong>function body</strong> is where you place a sequence of statements you want to execute.</p>
<h3 id="heading-syntax-of-a-javascript-function-body">Syntax of a JavaScript function body</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nameOfFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// function's body</span>
}
</code></pre>
<h3 id="heading-function-body-examples">Function body examples</h3>
<p>Below are examples of how we use the function body.</p>
<h4 id="heading-how-to-define-a-function-with-three-statements-in-its-body">How to define a function with three statements in its body</h4>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> firstName = <span class="hljs-string">"Oluwatobi"</span>;
  <span class="hljs-keyword">const</span> lastName = <span class="hljs-string">"Sofela"</span>;
  <span class="hljs-built_in">console</span>.log(firstName + <span class="hljs-string">" "</span> + lastName);
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-flz5tf?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, the function's body contains three statements that the computer will execute whenever the function gets invoked.</p>
<p><strong>Note:</strong> <code>console.log()</code> is a <a target="_blank" href="https://codesweetly.com/web-tech-terms-m#method">method</a> we use to log (write) messages to a web console.</p>
<h4 id="heading-how-to-define-a-function-with-two-statements-in-its-body">How to define a function with two statements in its body</h4>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bestColors = [<span class="hljs-string">"Coral"</span>, <span class="hljs-string">"Blue"</span>, <span class="hljs-string">"DeepPink"</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateMyBestColors</span>(<span class="hljs-params">previousColors, newColor</span>) </span>{
   <span class="hljs-keyword">const</span> mybestColors = [...previousColors, newColor];
   <span class="hljs-keyword">return</span> mybestColors;
}

updateMyBestColors(bestColors, <span class="hljs-string">"GreenYellow"</span>);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-nb9sr6?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, the function's body contains two statements that the computer will execute whenever the function gets invoked.</p>
<p><strong>Note:</strong></p>
<ul>
<li>The three dots we prepended to <code>previousColors</code> is called a <a target="_blank" href="https://codesweetly.com/spread-operator">spread operator</a>. We used it to expand the <a target="_blank" href="https://codesweetly.com/javascript-array-object">array</a> argument into individual elements.</li>
<li>You can also prepend the <code>newColor</code> parameter with a <a target="_blank" href="https://codesweetly.com/javascript-rest-operator">rest operator</a> if you wish to add two or more new colors.</li>
<li>The <code>return</code> keyword ends its function's execution and returns the specified <a target="_blank" href="https://codesweetly.com/javascript-statement#what-is-a-javascript-expression-statement">expression</a> (or <code>undefined</code> if you provide no expression).</li>
</ul>
<p>So, now that we know the components of a JavaScript function, we can discuss its types.</p>
<h2 id="heading-types-of-javascript-functions">Types of JavaScript Functions</h2>
<p>The four types of JavaScript functions are:</p>
<ul>
<li>Function declaration</li>
<li>Function expression</li>
<li>Arrow function expression</li>
<li>Immediately invoking function expression</li>
</ul>
<p>Let's discuss each type.</p>
<h2 id="heading-what-is-a-javascript-function-declaration">What Is a JavaScript Function Declaration?</h2>
<p>A <strong>function declaration</strong> is a function created without assigning it to a <a target="_blank" href="https://codesweetly.com/javascript-variable">variable</a>.</p>
<p><strong>Note:</strong> We sometimes call function declaration a "function definition" or "function statement."</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-number">100</span> + <span class="hljs-number">20</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-pwh2jr?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function above is a function declaration because we defined it without storing it in a variable.</p>
<h2 id="heading-what-is-a-javascript-function-expression">What Is a JavaScript Function Expression?</h2>
<p>A <strong>function expression</strong> is a function you create and assign to a variable.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-number">100</span> + <span class="hljs-number">20</span>;
};
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-hjg1iq?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function above is a <strong>named</strong> function expression that we assigned to the <code>myFuncExpr</code> variable.</p>
<p>You can also write the snippet above as an <strong>anonymous</strong> function expression like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-number">100</span> + <span class="hljs-number">20</span>;
};
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-pmeqy4?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function above is an anonymous function expression that we assigned to the <code>myFuncExpr</code> variable.</p>
<p><strong>Note:</strong></p>
<ul>
<li>An <strong>anonymous function</strong> is a function with no name.</li>
<li>A <strong>named function</strong> is a function with a name.</li>
</ul>
<p>A named function's main advantage is that the name makes it easier to trace an error's origin.</p>
<p>In other words, suppose your function threw an error. In such a case, if the function is named, a debugger's <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack">stack trace</a> will contain the function's name. Therefore, you will find it easier to identify the error's origin.</p>
<h2 id="heading-what-is-a-javascript-arrow-function-expression">What Is a JavaScript Arrow Function Expression?</h2>
<p>An <strong>arrow function expression</strong> is a shorthand way to write a function expression.</p>
<h3 id="heading-syntax-of-an-arrow-function">Syntax of an arrow function</h3>
<p>We define an arrow function with the equality and the greater-than symbols (<code>=&gt;</code>). Here is the syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> variableName = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// function's body</span>
}
</code></pre>
<h3 id="heading-example-of-an-arrow-function">Example of an arrow function</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-number">100</span> + <span class="hljs-number">20</span>;
};
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-1euhch?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>You can see that we defined the function without a <code>function</code> keyword and a function name.</p>
<p>You have to omit the <code>function</code> keyword and function name while writing an arrow function expression. Otherwise, JavaScript will throw a <code>SyntaxError</code>.</p>
<h3 id="heading-important-stuff-to-know-about-the-javascript-arrow-function-expression">Important stuff to know about the JavaScript arrow function expression</h3>
<p>Here are three essential facts to remember when using an arrow function expression.</p>
<h4 id="heading-1-the-parameters-parentheses-are-optional">1. The parameters' parentheses are optional</h4>
<p>Suppose your arrow function contains only a single parameter. In such a case, you can omit its parentheses.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function"><span class="hljs-params">a</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> a + <span class="hljs-number">20</span>;
};
</code></pre>
<p><a target="_blank" href="https://codepen.io/oluwatobiss/pen/OJQJejr"><strong>Try it on CodePen</strong></a></p>
<h4 id="heading-2-the-curly-brackets-and-return-keyword-are-optional">2. The curly brackets and <code>return</code> keyword are optional</h4>
<p>Suppose your arrow function contains only a single statement. In that case, you can omit its curly brackets and the <code>return</code> keyword.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> x + y;
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-8t2udu?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we implicitly returned the sum of parameters <code>x</code> and <code>y</code> by removing the curly brackets and the <code>return</code> keyword.</p>
<p><strong>Note:</strong> Whenever you choose to omit the curly brackets, also make sure that you remove the <code>return</code> keyword. Otherwise, the computer will throw a <code>SyntaxError</code>.</p>
<h4 id="heading-3-use-parentheses-to-wrap-any-implicit-object-return">3. Use parentheses to wrap any implicit object return</h4>
<p>Suppose you wish to return an object implicitly. In such a case, wrap the object in a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping">grouping operator</a> <code>(...)</code>.</p>
<p>For instance, consider the code below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-attr">carColor</span>: <span class="hljs-string">"White"</span>,
  <span class="hljs-attr">shoeColor</span>: <span class="hljs-string">"Yellow"</span>,
};
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/wrong-way-to-use-an-arrow-function-expression-to-return-an-object-implicitly-s8w132?file=/src/index.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above will throw a <code>SyntaxError</code> because JavaScript assumed the curly brackets (<code>{}</code>) to be the function body's code block—not an <a target="_blank" href="https://codesweetly.com/javascript-properties-object">object literal</a>.</p>
<p>Therefore, whenever you wish to return an object literal implicitly–without using the <code>return</code> keyword explicitly–make sure to encase the object literal in a grouping operator.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function">() =&gt;</span> ({
  <span class="hljs-attr">carColor</span>: <span class="hljs-string">"White"</span>,
  <span class="hljs-attr">shoeColor</span>: <span class="hljs-string">"Yellow"</span>,
});
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/correct-way-to-use-an-arrow-function-expression-to-return-an-object-implicitly-p61l5c?file=/src/index.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>Note that you can use the grouping operator to return any single value. For instance, the snippet below grouped the sum of <code>x</code> and <code>56</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> (x + <span class="hljs-number">56</span>);
</code></pre>
<p><a target="_blank" href="https://codepen.io/oluwatobiss/pen/rNJNXeG"><strong>Try it on CodePen</strong></a></p>
<p>Let's now discuss the fourth type of JavaScript function.</p>
<h2 id="heading-what-is-a-javascript-immediately-invoked-function-expression">What Is a JavaScript Immediately Invoked Function Expression?</h2>
<p>An <strong>immediately invoked function expression (IIFE)</strong> is a function expression that invokes itself automatically.</p>
<p><strong>Note:</strong> We sometimes call an IIFE a "Self-Invoking Function Expression" or "Self-Executing Anonymous Function Expression."</p>
<h3 id="heading-syntax-of-an-iife">Syntax of an IIFE</h3>
<pre><code class="lang-js">(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">/* ... */</span>
})();
</code></pre>
<p>An IIFE is composed of three main components:</p>
<ol>
<li><strong>A grouping operator:</strong> The first pair of parentheses <code>()</code></li>
<li><strong>A function:</strong> Enclosed within the grouping operator</li>
<li><strong>An invocator:</strong> The last pair of parentheses <code>()</code></li>
</ol>
<h3 id="heading-examples">Examples</h3>
<p>Below are examples of an IIFE.</p>
<h4 id="heading-how-to-define-a-named-iife">How to define a named IIFE</h4>
<pre><code class="lang-js">(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-number">100</span> + <span class="hljs-number">20</span>);
})();
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-nkjjnz?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function in the snippet above is a named self-invoking function expression.</p>
<h4 id="heading-how-to-define-an-anonymous-iife">How to define an anonymous IIFE</h4>
<pre><code class="lang-js">(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-number">100</span> + <span class="hljs-number">20</span>);
})();
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ywrmkt?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function in the snippet above is an anonymous self-invoking function expression.</p>
<h4 id="heading-how-to-define-an-arrow-function-iife">How to define an arrow function IIFE</h4>
<pre><code class="lang-js">(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-number">100</span> + <span class="hljs-number">20</span>))();
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-xqlfgi?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function in the snippet above is an arrow self-invoking function expression.</p>
<h4 id="heading-how-to-define-an-async-iife">How to define an async IIFE</h4>
<pre><code class="lang-js">(<span class="hljs-keyword">async</span> () =&gt; <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">await</span> <span class="hljs-number">100</span> + <span class="hljs-number">20</span>))();
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ryxftq?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function in the snippet above is an <a target="_blank" href="https://codesweetly.com/asynchronous-javascript">asynchronous</a> self-invoking function expression.</p>
<p>So, now that we know what an Immediately Invoked Function Expression is, we can discuss how it works.</p>
<h3 id="heading-how-does-an-iife-work">How does an IIFE work?</h3>
<p>By default, the computer does not know what <a target="_blank" href="https://codesweetly.com/javascript-data-types">data type</a> <a target="_blank" href="https://codesweetly.com/document-vs-data-vs-code#what-exactly-is-code">code</a> is until it evaluates it.</p>
<p>For instance, suppose you ask the computer to process <code>4</code>. In such a case, the system won't know if <code>4</code> is a number type until it evaluates it.</p>
<p>Therefore, JavaScript will throw a <code>SyntaxError</code> if you use any number method directly on <code>4</code>.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Convert 4 to a string value:</span>
<span class="hljs-number">4.</span>toString();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Uncaught SyntaxError: Invalid or unexpected token"</span>
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/how-iife-works-example-1-kc8g5b"><strong>Try it on CodeSandbox</strong></a></p>
<p>The computer threw a <code>SyntaxError</code> because it does not recognize <code>4</code> as a number data type.</p>
<p>However, suppose you assign <code>4</code> to a variable. In such a case, the computer will first convert it to a number data type before storing it into the variable.</p>
<p>Afterward, JavaScript will allow you to use any number methods on the number variable.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Assign 4 to a variable:</span>
<span class="hljs-keyword">const</span> myNum = <span class="hljs-number">4</span>;

<span class="hljs-comment">// Convert myNum's content to a string value:</span>
myNum.toString();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"4"</span>
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/how-iife-works-example-2-jz4kwi"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above did not return any error because JavaScript evaluated <code>myNum</code> as a number data type.</p>
<p>But you don't have to assign <code>4</code> to a variable before the computer can evaluate its data type appropriately.</p>
<p>You can alternatively put your value in <a target="_blank" href="https://www.computerhope.com/jargon/p/parenthe.htm">parentheses</a> to force the computer to evaluate its data type before using it for other things.</p>
<p>For instance, consider this snippet:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Evaluate 4's data type and turn it into a string value:</span>
(<span class="hljs-number">4</span>).toString();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"4"</span>
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/how-iife-works-example-3-rz4j9b"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above enclosed <code>4</code> in parentheses to make the computer evaluate its data type before using the <a target="_blank" href="https://codesweetly.com/javascript-number-tostring-method"><code>toString()</code></a> method to convert it to a string value.</p>
<p>Using parentheses to make JavaScript evaluate your code's data type first is what happens in an Immediately Invoking Function Expression (IIFE).</p>
<p>For instance, consider this example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Evaluate the function's data type and immediately invoke it:</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-number">100</span> + <span class="hljs-number">20</span>);
})();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-number">120</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-nkjjnz?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above enclosed the <code>addNumbers</code> function in parentheses to make the computer evaluate its data type before invoking it immediately after the evaluation.</p>
<h2 id="heading-overview">Overview</h2>
<p>In this article, we discussed what a JavaScript function object is. We also used examples to see how it works.</p>
<p>Thanks for reading.</p>
<h3 id="heading-and-heres-a-useful-reactjs-resource"><strong>And here's a useful ReactJS resource:</strong></h3>
<p>I wrote a book about React!</p>
<ul>
<li>It's beginner friendly ✔</li>
<li>It has live code snippets ✔</li>
<li>It contains scalable projects ✔</li>
<li>It has plenty of easy-to-grasp examples ✔</li>
</ul>
<p>The <a target="_blank" href="https://www.amazon.com/dp/B09KYGDQYW">React Explained Clearly</a> book is all you need to understand ReactJS.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B09KYGDQYW"><img src="https://www.freecodecamp.org/news/content/images/2022/01/Twitter-React_Explained_Clearly-CodeSweetly-Oluwatobi_Sofela.jpg" alt="React Explained Clearly Book Now Available at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Programming Paradigms – Paradigm Examples for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article we're going to take a look at programming paradigms, a fancy title to describe popular ways or styles to organize your programming. I'll try to break it down in pieces and give a simple explanation of each paradigm. This ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-introduction-to-programming-paradigms/</link>
                <guid isPermaLink="false">66d45edd9208fb118cc6cf95</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Mon, 02 May 2022 16:42:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/anne-nygard-OJzEnupZWGM-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article we're going to take a look at programming paradigms, a fancy title to describe popular ways or styles to organize your programming.</p>
<p>I'll try to break it down in pieces and give a simple explanation of each paradigm. This way you can understand what people are talking about when they say "object oriented", "functional" or "declarative".</p>
<p>This will be a superficial and brief theoretical introduction more than anything else, though we're going to see some pseudo-code and code examples too.</p>
<p>I plan to explore each paradigm in depth with practical JavaScript examples in the future, so follow me (links at the bottom) if you're interested in that kind of article. ;)</p>
<p>Let's go!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-programming-paradigm">What is a programming paradigm</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-a-programming-paradigm-is-not">What a programming paradigm is not</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-should-i-care">Why should I care?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-popular-programming-paradigms">Popular programming paradigms</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-imperative-programming">Imperative programming</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-procedural-programming">Procedural programming</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-functional-programming">Functional programming</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-declarative-programming">Declarative programming</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-object-oriented-programming">Object-oriented programming</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-roundup">Roundup</a></p>
</li>
</ul>
<h1 id="heading-what-is-a-programming-paradigm">What is a Programming Paradigm?</h1>
<p>Programming paradigms are different ways or styles in which a given program or programming language can be organized. Each paradigm consists of certain structures, features, and opinions about how common programming problems should be tackled.</p>
<p>The question of why are there many different programming paradigms is similar to why are there many programming languages. Certain paradigms are better suited for certain types of problems, so it makes sense to use different paradigms for different kinds of projects.</p>
<p>Also, the practices that make up each paradigm have developed through time. Thanks to the advances both in software and hardware, different approaches have come up that didn't exist before.</p>
<p>And last I think, there's human creativity. As a species, we just like creating things, improving what others have built in the past, and adapting tools to our preference or to what seems more efficient to us.</p>
<p>All this results in the fact that today we have many options to choose from when we want to write and structure a given program. 🥸</p>
<h1 id="heading-what-a-programming-paradigm-is-not">What a Programming Paradigm is Not</h1>
<p>Programming paradigms are not languages or tools. You can't "build" anything with a paradigm. They're more like a set of ideals and guidelines that many people have agreed on, followed, and expanded upon.</p>
<p>Programming languages aren't always tied to a specific paradigm. There are languages that have been built with a certain paradigm in mind and have features that facilitate that kind of programming more than others (<a target="_blank" href="https://www.haskell.org/">Haskel</a> and functional programming is a good example).</p>
<p>But there are also "multi-paradigm" languages, meaning you can adapt your code to fit a certain paradigm or another (JavaScript and Python are good examples).</p>
<p>At the same time, programming paradigms aren't mutually exclusive, in the sense that you could use practices from different paradigms at the same time with no problem at all.</p>
<h1 id="heading-why-should-i-care">Why should I care?</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/whatever-yeah-1.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Short answer: general knowledge.</p>
<p>Long answer: I find that it's interesting to understand the many ways in which programming can be done. Exploring these topics is a good way of opening your mind and helping you think outside the box and outside the tools you already know.</p>
<p>Moreover, these terms are used a lot in the coding world, so having a basic understanding will help you better understand other topics as well.</p>
<h1 id="heading-popular-programming-paradigms">Popular Programming Paradigms</h1>
<p>Now that we have introduced what programming paradigms are and are not, let's go through the most popular ones, explain their main characteristics, and compare them.</p>
<p>Keep in mind this list is not exhaustive. There are other programming paradigms not covered here, although I'll be covering the most popular and most widely-used ones.</p>
<h2 id="heading-imperative-programming">Imperative Programming</h2>
<p>Imperative programming consists of sets of detailed instructions that are given to the computer to execute in a given order. It's called "imperative" because as programmers we dictate exactly what the computer has to do, in a very specific way.</p>
<p>Imperative programming focuses on describing <em>how</em> a program operates, step by step.</p>
<p>Say you want to bake a cake. Your imperative program to do this might look like this (I'm not a great cook, so don't judge me 😒):</p>
<pre><code class="lang-plaintext">1- Pour flour in a bowl
2- Pour a couple eggs in the same bowl
3- Pour some milk in the same bowl
4- Mix the ingredients
5- Pour the mix in a mold
6- Cook for 35 minutes
7- Let chill
</code></pre>
<p>Using an actual code example, let's say we want to filter an array of numbers to only keep the elements bigger than 5. Our imperative code might look like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nums = [<span class="hljs-number">1</span>,<span class="hljs-number">4</span>,<span class="hljs-number">3</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">2</span>]
<span class="hljs-keyword">const</span> result = []

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; nums.length; i++) {
    <span class="hljs-keyword">if</span> (nums[i] &gt; <span class="hljs-number">5</span>) result.push(nums[i])
}

<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// Output: [ 6, 7, 8, 9 ]</span>
</code></pre>
<p>See that we're telling the program to iterate through each element in the array, compare the item value with 5, and if the item is bigger than 5, push it into an array.</p>
<p>We're being detailed and specific in our instructions, and that's what imperative programming stands for.</p>
<h2 id="heading-procedural-programming">Procedural Programming</h2>
<p>Procedural programming is a derivation of imperative programming, adding to it the feature of functions (also known as "procedures" or "subroutines").</p>
<p>In procedural programming, the user is encouraged to subdivide the program execution into functions, as a way of improving modularity and organization.</p>
<p>Following our cake example, procedural programming may look like this:</p>
<pre><code class="lang-plaintext">function pourIngredients() {
    - Pour flour in a bowl
    - Pour a couple eggs in the same bowl
    - Pour some milk in the same bowl
}

function mixAndTransferToMold() {
    - Mix the ingredients
    - Pour the mix in a mold
}

function cookAndLetChill() {
    - Cook for 35 minutes
    - Let chill
}

pourIngredients()
mixAndTransferToMold()
cookAndLetChill()
</code></pre>
<p>You can see that, thanks to the implementation of functions, we could just read the three function calls at the end of the file and get a good idea of what our program does.</p>
<p>That simplification and abstraction is one of the benefits of procedural programming. But within the functions, we still got same old imperative code.</p>
<h2 id="heading-functional-programming">Functional Programming</h2>
<p>Functional programming takes the concept of functions a little bit further.</p>
<p>In functional programming, functions are treated as <strong>first-class citizens</strong>, meaning that they can be assigned to variables, passed as arguments, and returned from other functions.</p>
<p>Another key concept is the idea of <strong>pure functions</strong>. A <strong>pure</strong> function is one that relies only on its inputs to generate its result. And given the same input, it will always produce the same result. Besides, it produces no side effects (any change outside the function's environment).</p>
<p>With these concepts in mind, functional programming encourages programs written mostly with functions (surprise 😲). It also defends the idea that code modularity and the absence of side effects makes it easier to identify and separate responsibilities within the codebase. This therefore improves the code maintainability.</p>
<p>Going back to the array filtering example, we can see that with the imperative paradigm we might use an external variable to store the function's result, which can be considered a side effect.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nums = [<span class="hljs-number">1</span>,<span class="hljs-number">4</span>,<span class="hljs-number">3</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">2</span>]
<span class="hljs-keyword">const</span> result = [] <span class="hljs-comment">// External variable</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; nums.length; i++) {
    <span class="hljs-keyword">if</span> (nums[i] &gt; <span class="hljs-number">5</span>) result.push(nums[i])
}

<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// Output: [ 6, 7, 8, 9 ]</span>
</code></pre>
<p>To transform this into functional programming, we could do it like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nums = [<span class="hljs-number">1</span>,<span class="hljs-number">4</span>,<span class="hljs-number">3</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">2</span>]

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">filterNums</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> result = [] <span class="hljs-comment">// Internal variable</span>

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; nums.length; i++) {
        <span class="hljs-keyword">if</span> (nums[i] &gt; <span class="hljs-number">5</span>) result.push(nums[i])
    }

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

<span class="hljs-built_in">console</span>.log(filterNums()) <span class="hljs-comment">// Output: [ 6, 7, 8, 9 ]</span>
</code></pre>
<p>It's almost the same code, but we wrap our iteration within a function, in which we also store the result array. In this way, we can assure the function doesn't modify anything outside its scope. It only creates a variable to process its own information, and once the execution is finished, the variable is gone too.</p>
<h2 id="heading-declarative-programming">Declarative Programming</h2>
<p>Declarative programming is all about hiding away complexity and bringing programming languages closer to human language and thinking. It's the direct opposite of imperative programming in the sense that the programmer doesn't give instructions about <em>how</em> the computer should execute the task, but rather on <em>what</em> result is needed.</p>
<p>This will be much clearer with an example. Following the same array filtering story, a declarative approach might be:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nums = [<span class="hljs-number">1</span>,<span class="hljs-number">4</span>,<span class="hljs-number">3</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">2</span>]

<span class="hljs-built_in">console</span>.log(nums.filter(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num &gt; <span class="hljs-number">5</span>)) <span class="hljs-comment">// Output: [ 6, 7, 8, 9 ]</span>
</code></pre>
<p>See that with the filter function, we're not explicitly telling the computer to iterate over the array or store the values in a separate array. We just say what we want ("filter") and the condition to be met ("num &gt; 5").</p>
<p>What's nice about this is that it's easier to read and comprehend, and often shorter to write. JavaScript's <code>filter</code>, <code>map</code>, <code>reduce</code> and <code>sort</code> functions are good examples of declarative code.</p>
<p>Another good example are modern JS frameworks/libraries like React. Take this code for example:</p>
<pre><code class="lang-javascript">&lt;button onClick={<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'You clicked me!'</span>)}&gt;Click me&lt;/button&gt;
</code></pre>
<p>Here we have a button element, with an event listener that fires a console.log function when the button is clicked.</p>
<p>JSX syntax (what React uses) mixes HTML and JS in the same thing, which makes it easier and faster to write apps. But that's not what browsers read and execute. React code is later on transpiled into regular HTML and JS, and that's what browsers run in reality.</p>
<p>JSX is declarative, in the sense that its purpose is to give developers a friendlier and more efficient interface to work with.</p>
<p>An important thing to notice about declarative programming is that under the hood, the computer processes this information as imperative code anyway.</p>
<p>Following the array example, the computer still iterates over the array like in a for loop, but as programmers we don't need to code that directly. What declarative programming does is to <strong>hide away</strong> that complexity from the direct view of the programmer.</p>
<p>Here's a nice <a target="_blank" href="https://www.youtube.com/watch?v=E7Fbf7R3x6I">comparison between imperative and declarative programming.</a></p>
<h2 id="heading-object-oriented-programming">Object-Oriented Programming</h2>
<p>One of the most popular programming paradigms is object-oriented programming (OOP).</p>
<p>The core concept of OOP is to separate concerns into entities which are coded as objects. Each entity will group a given set of information (properties) and actions (methods) that can be performed by the entity.</p>
<p>OOP makes heavy usage of classes (which are a way of creating new objects starting out from a blueprint or boilerplate that the programmer sets). Objects that are created from a class are called instances.</p>
<p>Following our pseudo-code cooking example, now let's say in our bakery we have a main cook (called Frank) and an assistant cook (called Anthony) and each of them will have certain responsibilities in the baking process. If we used OOP, our program might look like this.</p>
<pre><code class="lang-plaintext">// Create the two classes corresponding to each entity
class Cook {
    constructor constructor (name) {
        this.name = name
    }

    mixAndBake() {
        - Mix the ingredients
        - Pour the mix in a mold
        - Cook for 35 minutes
    }
}

class AssistantCook {
    constructor (name) {
        this.name = name
    }

    pourIngredients() {
        - Pour flour in a bowl
        - Pour a couple eggs in the same bowl
        - Pour some milk in the same bowl
    }

    chillTheCake() {
        - Let chill
    }
}

// Instantiate an object from each class
const Frank = new Cook('Frank')
const Anthony = new AssistantCook('Anthony')

// Call the corresponding methods from each instance
Anthony.pourIngredients()
Frank.mixAndBake()
Anthony.chillTheCake()
</code></pre>
<p>What's nice about OOP is that it facilitates the understanding of a program, by the clear separation of concerns and responsibilities.</p>
<p>In this example I've just scratched the surface of the many features of OOP. If you'd like to know more, here are two great videos explaining the basics of OOP:</p>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=cg1xvFy1JQQ">OOP video 1</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=pTB0EiLXUC8">OOP video 2</a></p>
</li>
</ul>
<p>And <a target="_blank" href="https://www.youtube.com/watch?v=08CWw_VD45w">here's a nice comparison between imperative, functional and object-oriented programming.</a></p>
<h2 id="heading-roundup">Roundup</h2>
<p>As we've seen, programming paradigms are different ways in which we can face programming problems, and organize our code.</p>
<p>Imperative, procedural, functional, declarative, and object oriented paradigms are some of the most popular and widely used paradigms today. And knowing the basics about them is good for general knowledge and also for better understanding other topics of the coding world.</p>
<p>As always, I hope you enjoyed the article and learned something new. If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">linkedin</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">twitter</a>.</p>
<p>Cheers and see you in the next one! =D</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/200.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Pure vs Impure Functions in Functional Programming – What's the Difference? ]]>
                </title>
                <description>
                    <![CDATA[ Pure functions and impure functions are two programming terms you will often see in functional programming. One core difference between these two types of functions is whether or not they have side effects. In this article, you will learn what side e... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/pure-function-vs-impure-function/</link>
                <guid isPermaLink="false">66ba0e0b7fb82b484b253a2f</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Mon, 09 Aug 2021 21:06:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/pure-function-vs-impure-function-codesweetly.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Pure functions and impure functions are two programming terms you will often see in functional programming.</p>
<p>One core difference between these two types of functions is whether or not they have side effects.</p>
<p>In this article, you will learn what side effects are and we'll discuss the differences between pure and impure functions.</p>
<p>Without any further ado, let's get started with side effects.</p>
<h2 id="heading-what-is-a-side-effect">What is a Side Effect?</h2>
<p>A <strong>side effect</strong> occurs in a program whenever you use <em>external code</em> in your function — which, as a result, impacts the function’s ability to perform its task.</p>
<p>So what exactly does this mean? Let's see with some examples.</p>
<h3 id="heading-side-effect-example-1-how-to-add-an-old-value-to-a-new-one">Side Effect Example 1: How to add an old value to a new one</h3>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> oldDigit = <span class="hljs-number">5</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumber</span>(<span class="hljs-params">newValue</span>) </span>{
  <span class="hljs-keyword">return</span> oldDigit += newValue;
}
</code></pre>
<p>In the snippet above, <code>oldDigit</code>’s usage within the function gives <code>addNumber()</code> the following side effects:</p>
<h4 id="heading-first-side-effect-dependency-on-olddigit">First side effect: Dependency on oldDigit</h4>
<p>The fact that <code>addNumber()</code> depends on <code>oldDigit</code> to successfully perform its duties means that whenever <code>oldDigit</code> is not available (or <code>undefined</code>), <code>addNumber()</code> will return an error.</p>
<h4 id="heading-second-side-effect-modifies-external-code">Second side effect: Modifies external code</h4>
<p>As <code>addNumber()</code> is programmed to mutate <code>oldDigit</code>’s <a target="_blank" href="https://www.codesweetly.com/state-in-programming/">state</a>, which implies that <code>addNumber()</code> has a side effect of manipulating some external code.</p>
<h4 id="heading-third-becomes-a-non-deterministic-function">Third: Becomes a non-deterministic function</h4>
<p>Using external code in <code>addNumber()</code> makes it a non-deterministic function — as you can never determine its output by solely reading it.</p>
<p>In other words, to be sure of <code>addNumber()</code>’s return value, you must consider other external factors — such as the current state of <code>oldDigit</code>.</p>
<p>Therefore, <code>addNumber()</code> is not independent — it always has strings attached.</p>
<h3 id="heading-side-effect-example-2-how-to-print-text-to-your-console">Side Effect Example 2: How to print text to your console</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"My name is Oluwatobi Sofela."</span>);
}
</code></pre>
<p>In the snippet above, <code>console.log()</code>’s usage within <code>printName()</code> gives the function side effects.</p>
<h4 id="heading-how-does-consolelog-cause-a-function-to-have-side-effects">How does console.log cause a function to have side effects?</h4>
<p>A <code>console.log()</code> causes a function to have side effects because it affects the state of external code — that is, the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/console">console object</a>'s state.</p>
<p>In other words, <code>console.log()</code> instructs the computer to alters the <code>console</code> object's state.</p>
<p>As such, when you use it within a function, it causes that function to:</p>
<ol>
<li>Be dependent on the <code>console</code> object to perform its job effectively.</li>
<li>Modify the state of an external code (that is, the <code>console</code> object’s state).</li>
<li>Become non-deterministic — as you must now consider the <code>console</code>’s state to be sure of the function’s output.</li>
</ol>
<p>Therefore, whenever you use <em>external code</em> in your function, that code will cause <strong>side effects</strong>.</p>
<p>So how do side effects relate to pure and impure functions?</p>
<p>Let’s find out by looking at the definition of a pure function and its impure alternative.</p>
<h2 id="heading-what-is-an-impure-function">What is an Impure Function?</h2>
<p>So now that we know what side effects in functions are, we can talk about impure (and pure) functions.</p>
<p>First, an <strong>impure function</strong> is a function that contains one or more side effects. </p>
<p>Consider the JavaScript code below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myNames = [<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateMyName</span>(<span class="hljs-params">newName</span>) </span>{
  myNames.push(newName);
  <span class="hljs-keyword">return</span> myNames;
}
</code></pre>
<p>In the snippet above, <code>updateMyName()</code> is an impure function because it contains code (<code>myNames</code>) that mutates an external <a target="_blank" href="https://www.codesweetly.com/state-in-programming/">state</a> — which gives <code>updateMyName()</code> some side effects.</p>
<h2 id="heading-what-is-a-pure-function">What is a Pure Function?</h2>
<p>A <strong>pure function</strong> is a function without any side effects.</p>
<p>Consider the JavaScript code below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateMyName</span>(<span class="hljs-params">newName</span>) </span>{
   <span class="hljs-keyword">const</span> myNames = [<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>];
   myNames[myNames.length] = newName;
   <span class="hljs-keyword">return</span> myNames;
}
</code></pre>
<p>In the snippet above, notice that <code>updateMyName()</code> does not depend on any external code to accomplish its duties. This makes it a <em>pure function</em>.</p>
<p>Wherever possible, you should use pure functions in your applications. Let's discuss some of the advantages you get by doing so.</p>
<h2 id="heading-advantages-of-pure-functions">Advantages of Pure Functions</h2>
<p>The following are some advantages of pure functions.</p>
<h3 id="heading-pure-functions-are-independent">Pure functions are independent</h3>
<p>Pure functions do not affect any external state, and they are also not affected by external code.</p>
<p>In other words, all external data a pure function uses gets received as parameters — they are not <em>explicitly used internally</em>.</p>
<p>Therefore, what you see within is what you get — there are absolutely no strings attached.</p>
<p>As such, you don’t need to look for external conditions (states) that might impact your pure function's effective operation as all activities happen within.</p>
<h3 id="heading-pure-functions-are-easier-to-read">Pure functions are easier to read</h3>
<p>Pure functions are easier to read and debug than their impure alternatives.</p>
<p>Pure functions are so readable because they are solely dependent on themselves — they neither affect nor are they impacted by external states.</p>
<h2 id="heading-important-stuff-to-know-about-pure-functions">Important Stuff to Know about Pure Functions</h2>
<p>Keep these three essential pieces of info in mind whenever you choose to use pure functions.</p>
<h3 id="heading-you-can-clone-an-external-state-into-a-pure-function">You can clone an external state into a pure function</h3>
<p>Cloning an external state into a pure function does not make the function impure.</p>
<p>State duplication is simply a copy-and-paste operation that does not leave any strings attached between the source and its clone.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myBio = [<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateMyBio</span>(<span class="hljs-params">newBio, array</span>) </span>{
  <span class="hljs-keyword">const</span> clonedBio = [...array];
  clonedBio[clonedBio.length] = newBio;
  <span class="hljs-keyword">return</span> clonedBio;
}

<span class="hljs-built_in">console</span>.log(updateMyBio(<span class="hljs-string">"codesweetly.com"</span>, myBio));
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-blhtpi?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, <code>updateMyBio()</code> used the <a target="_blank" href="https://www.codesweetly.com/spread-operator/">spread operator</a> to duplicate <code>myBio</code>’s state into <code>clonedBio</code>. However, it is still a pure function because it is neither dependent on <code>myBio</code> nor does it modify any external code.</p>
<p>Instead, it is an exclusively deterministic function programmed to use the cloned version of its array parameter.</p>
<h3 id="heading-avoid-code-mutations-in-pure-functions">Avoid code mutations in pure functions</h3>
<p>Technically, you can mutate variables defined locally within a pure function’s scope. However, it is best to avoid doing so.</p>
<p>For instance, consider the code below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> compBio = [<span class="hljs-string">"code"</span>, <span class="hljs-string">"sweetly"</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateCompBio</span>(<span class="hljs-params">newBio, array</span>) </span>{
  <span class="hljs-keyword">const</span> clonedBio = [...array];
  clonedBio[clonedBio.length] = newBio;
  <span class="hljs-keyword">return</span> clonedBio;
}

<span class="hljs-built_in">console</span>.log(updateCompBio(<span class="hljs-string">".com"</span>, compBio));
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-dprdlf?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, <code>updateCompBio()</code> is a pure function that uses <code>clonedBio[clonedBio.length] = newBio</code> to alter its local state.</p>
<p>Although such an operation does not make <code>updateCompBio()</code> impure, it is not the best practice.</p>
<p>The recommended way to write a pure function is to make it receive <em>all</em> its values as parameters like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> compBio = [<span class="hljs-string">"code"</span>, <span class="hljs-string">"sweetly"</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateCompBio</span>(<span class="hljs-params">newBio, array</span>) </span>{
  <span class="hljs-keyword">return</span> [...array, newBio];
}

<span class="hljs-built_in">console</span>.log(updateCompBio(<span class="hljs-string">".com"</span>, compBio));
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-gyl8sy?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Notice how clean and portable our code now looks. This is an advantage of making your pure function receive all its values as parameters. By so doing, you will also find it easier to debug your code.</p>
<h3 id="heading-the-same-input-will-always-return-the-same-output">The same input will always return the same output</h3>
<p>A vital trait about pure functions is that they will always return the same value with the same set of inputs — no matter how many times you invoke them.</p>
<h2 id="heading-wrapping-it-up">Wrapping it up</h2>
<p>Your function is <strong>pure</strong> if it does not contain any external code. Otherwise, it is <strong>impure</strong> if it includes one or more side effects.</p>
<p>In this article we discussed what pure and impure functions are, and we learned about the advantages using pure functions can bring to your code.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Implement the Paxos Algorithm in Pure Functions ]]>
                </title>
                <description>
                    <![CDATA[ By Edward Huang Imagine that you are on a football team. After practice, the team loves to go out together and eat.  Let's say that the team usually wants to eat pizza or burgers. However, you want the whole team to go out to the same place after pra... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-implement-paxos-algorithm-in-pure-functions/</link>
                <guid isPermaLink="false">66d84fd8e9c1a2c18adec097</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 29 Mar 2021 18:06:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/03/Paxos-Made-Functional-Background-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Edward Huang</p>
<p>Imagine that you are on a football team. After practice, the team loves to go out together and eat. </p>
<p>Let's say that the team usually wants to eat pizza or burgers. However, you want the whole team to go out to the same place after practice because it is more fun that way.</p>
<p>Therefore, you need to get the team to agree on the football field where everyone is going – getting burgers or pizza.</p>
<p>But there is one problem: the coach went home early. Everyone is exhausted and hungry after the practice, so they got easily distracted and want to come to a decision fast. </p>
<p>Moreover, you cannot yell at the football field because the entire team tends to talk really loudly, and your suggestion might be easily overwritten by another person.</p>
<p>You must be thinking, "There is only one way that I can achieve this agreement – through person-to-person communication, and want everyone to achieve a consensus."</p>
<p>How are you going to solve this?</p>
<p>This analogy is the same problem that we encounter in distributed systems, but you are dealing with many servers this time. We want to make many servers agree on common events or common information in an asynchronous environment.</p>
<p>You can use many algorithms to solve the problems, and today we will talk about one of them: the Paxos Algorithm. </p>
<p>Paxos is one of the earliest published papers about this distributed consensus algorithm that runs rounds and rounds of times to help many servers agree on a value proposed by a group member.</p>
<p>The algorithm uses peer-to-peer communication, where each peer can be in three roles, the proposer, the acceptor, and the learner. These roles don't have to be separated on each server – meaning a server can have the role of the learner, the acceptor, and the proposer at the same time.</p>
<p>Going back to the Football analogy above, for simplicity, we separate the three roles. Half the team can be the proposer, a quarter can be the acceptor, and a quarter can be the learner.</p>
<p>The proposer can propose where they want to go eat to the acceptor. The acceptor will have some criteria to determine based on each proposed value which place they will choose. Once the acceptor chooses the majority of the proposed messages, they will send it to the learner. </p>
<p>For instance, one of the acceptors elects a burger. They tell the learner that the majority of the team wants to eat burger. However, this is where it gets interesting: another acceptor elects a pizza, and they tell the learner that the majority of the team wants to eat pizza. </p>
<p>Therefore, it is up to the learner to announce based on the message they receive from all the acceptors what the majority really wants to eat. The algorithm will keep running multiple iterations until the learner announces the consensus.</p>
<p>I will explain the Paxos algorithm later in this article in more detail along with its implementation. By the end of this article, you will know how a replication state machine in a distributed system really works and the main algorithm used in the Chubby <a target="_blank" href="https://static.googleusercontent.com/media/research.google.com/en//archive/chubby-osdi06.pdf">protocol</a>.</p>
<h2 id="heading-before-we-start">Before we start</h2>
<p>In this article, we won't discuss the "why" and the steps the algorithm goes through to reach consensus. If you are interested in why the Paxos Algorithm works, you can look at a great brief introduction in this Google <a target="_blank" href="https://www.youtube.com/watch?v=d7nAGI_NZPk">Tech Talk</a>. </p>
<p>Secondly, I assume that the proof and the theory works, and this article will be mainly about the implementation.</p>
<h2 id="heading-a-brief-introduction-to-the-paxos-algorithm">A Brief Introduction to the Paxos Algorithm</h2>
<p>There are 3 roles in the Paxos algorithm – the proposer, the acceptors, and the learner. </p>
<p>The proposer will propose a value by sending messages to another member of the group.</p>
<p>Acceptors will accept the proposed value.</p>
<p>The learner learns whether the group has reached consensus in a particular round of the algorithm.</p>
<p>The Paxos Algorithm takes in two phases (the prepare phase and accept phase) as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Paxos-Role-Simple-Diagram.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-prepare-phase">The Prepare Phase</h3>
<p>Each group's proposers select a proposal number and send a prepared request to the system's acceptor. The message doesn't need to be received by all of them. It just needs to be the majority (a quorum) for the algorithm to proceed.</p>
<p>The acceptor who receives this message will make a comparison with the current highest proposal number. If the incoming request is higher than the proposal number, it will accept and sends a hopeful message back saying to the proposal, "okay, your proposal is higher than what I currently have, so I will choose you." </p>
<p>If the acceptor already accepts a message, it will send the same thing, except it will say, "okay, your proposal is higher than what I currently have. However, I have already accepted a message proposal. I'm going to attach that proposal number and value in the message too." </p>
<p>If the acceptor receives the message with a lower proposal number, it will simply ignore it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Prepare-Phase.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-accept-phase">The Accept Phase</h3>
<p>If the proposer receives a majority's promise response, it will check if any promised messages have an accepted message. If it has an accept message, the proposal will accept the message to send the accept request to the processor again.</p>
<p>Suppose the proposer doesn't receive responses from most acceptors to which it broadcasts its message. In that case, it will simply assume that "my proposal number is not high enough, I'm going to create a higher proposal number and broadcast it again to the acceptor."</p>
<p>If the proposer receives responses from the majority of the acceptors, it will inform the learner that it has reached a consensus.</p>
<p>Suppose an acceptor receives an accept request with the proposal number equal to its promises. In that case, it will send back a confirmation to that proposer that the proposal value is accepted. </p>
<p>If an acceptor receives an accept request with the proposal number less than the prepared request, it simply ignores it.</p>
<p>On the learner side, once it receives the majority (quorum) of value coming from the proposal, it will mark that it has reached a consensus.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Accept-Case.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In theory, it sounds simple. However, in practice, it has lots of cases that need to be accounted for. A couple of <a target="_blank" href="https://static.googleusercontent.com/media/research.google.com/en//archive/paxos_made_live.pdf">papers</a> talk about their experience in implementing Paxos in their production systems. </p>
<p>I saw many sources implement Paxos based on an object-oriented language, such as the Java <a target="_blank" href="https://github.com/cocagne/paxos#cocagnepaxosessential">implementation</a> or implementation with the <a target="_blank" href="https://github.com/ahanwadi/paxos">actor system</a>. So I thought, "why not try to implement one in functional programming terms?" </p>
<p>Please note that this implementation is based on the Paxos-made simple algorithm paper. It doesn't have any fancy invariant such as an account for machine failure, leader election, and so on. This implementation also implements a single-round basic Paxos algorithm.</p>
<h2 id="heading-the-challenge">The Challenge</h2>
<h3 id="heading-model-construction">Model Construction</h3>
<p>The essence of the Paxos algorithm is communication between nodes. Therefore, it will be the most intuitive to model the role as objects. </p>
<p>Since it mentions how proposers, acceptors, and learners interact, an actor system is the easiest way to create the algorithm. We can have 3 actors and encapsulate the logic and state within the actors. </p>
<h3 id="heading-immutable-state-management">Immutable State Management</h3>
<p>This can be a challenge if we want to implement something immutable by nature because the algorithm requires a constant change in the internal state.<br>Object-oriented programming can encapsulate the state management for proposers, acceptors, and learners. On each of these phases, we can mutate the state inside each instance.<br>For instance, an acceptors instance can have a max_id as a mutable internal state, and it can change the max_id if it receives a prepared message that contains a higher id number. </p>
<h2 id="heading-how-to-implement-the-paxos-algorithm-functionally">How to Implement the Paxos Algorithm Functionally</h2>
<p>Let's discuss how to implement the Paxos algorithm functionally, and how to design that implementation. I will use Scala and leverage the cats' data library to not reinvent the wheel of creating its own monad instances and its law.</p>
<h3 id="heading-domain-models">Domain Models</h3>
<p>Let's start with each of the domain models. The simplest way to do this is to visualize what the proposer, acceptor, and learner needs.</p>
<h3 id="heading-proposer-model">Proposer Model</h3>
<p>The proposer will consist of a value, a proposal number, and a quorum size. The proposal number needs to be unique and in increasing number. The common way to implement this proposal number is an id with a machine-id to ensure uniqueness. </p>



<p>The compare statement is equivalent to a Java comparator where you can check if one is equal to another.</p>
<p>The quorum size is the number of nodes in the system. </p>
<h3 id="heading-acceptor-model">Acceptor Model</h3>
<p>The acceptor consists of a promise proposal number and the proposal number and value it accepts. Since those two values might not exist, let's make them optional.</p>


<h3 id="heading-learner-model">Learner Model</h3>
<p>The learner needs to keep track of all the accepted responses that it receives and check if the incoming value is over the majority. Therefore, it needs to have a key-value mapping to keep track of those counts. </p>
<p>The key will be the accepted value, and the value will be the number of counts. To know the majority, it needs to have the quorum size. Also, there needs to be a way to chose a value when it is above the majority.  </p>
<p>Therefore, the learner will have a quorum size, a mapping for accepted values so far, and the final value that is chosen.</p>


<p>Usually, in OOP, we will put the functions inside the model, and its function will mutate the state of the model. </p>
<p>Functionally, I decided to separate the functions into their own object, <code>Ops</code>, that can interact with the proposer. These separate the model and the operation so that we separate the concerns on state mutation. </p>
<h3 id="heading-messages">Messages</h3>
<p>Next, we will think about the message type to communicate for each two-phase algorithm. There are four message types total:</p>
<ul>
<li><code>messagePreapre</code> </li>
<li><code>messagePromise</code></li>
<li><code>messageAccept</code> </li>
<li><code>messageAccepted</code></li>
</ul>
<p>Let's combine these messages as a sealed trait.</p>


<p>Since an acceptor possibly has not accepted any proposal when responding to a promise request, we will use an Option type to embed the <code>AcceptedValue</code> in the <code>Accept</code> message.</p>
<h3 id="heading-action">Action</h3>
<p>One of the benefits of implementing Paxos or any other consensus algorithm in pure functions is that we start thinking of putting all the side effects IO in one component. </p>
<p>There are many ways to push IO's boundary to the <a target="_blank" href="https://stackoverflow.com/questions/13340458/what-does-the-world-mean-in-functional-programming-world">end of the world</a>. However, one easy way to do this is to change the statement into a value. </p>
<p>Therefore, we will define an <code>Action</code> type in the implementation. This <code>Action</code> type will be a value type that describes any impure side effects required by the protocol. </p>
<p>For instance, in Paxos, the protocol's side effect sends messages to other machines and processes. Therefore, this action type contains <code>Broadcast</code> and <code>Send</code>, which will broadcast the proposer either the acceptor group or the learner group. </p>
<p>Therefore the Action co-product will have something like this:</p>


<h3 id="heading-how-to-create-a-pure-message-handling-logic">How to Create a Pure Message Handling Logic</h3>
<p>Once we separate the algorithm's impure effects, we can focus on the algorithm's core state management.  </p>
<p>How do we manage to have state management without mutation?</p>
<p>One way to do this is that each function will be wrapped in a <code>State</code> monad. A state monad is a monad that takes in the previous state, and it returns a new state with some results. </p>
<p>If you are not familiar with it, check out my previous blog post about state monads <a target="_blank" href="https://edward-huang.com/scala/functional-programming/monad/programming/2020/12/21/must-know-patterns-for-constructing-stateful-programs-without-any-mutation/">here</a>.</p>
<p>Therefore, we can have a function that has a wrapper of <code>State[Proposer, Action]</code>, which translates to <code>Proposer =&gt; (Proposer,Action)</code>.</p>
<p>To simplify the design, I created three <code>Ops</code> objects – <code>ProposerOps</code>, <code>AcceptorOps</code>, and <code>LearnerOps</code> – to simplify the implementation's design. </p>
<p>This kind of design is influenced by how the actor system or object-oriented way of implementing the algorithm separates each of the operations inside the role's object. The code is more modular and clean this way.</p>


<p>Each of the function operations inside the <code>Ops</code> object class will do the action to mutate the role. </p>
<p>For instance, let's take a look at the prepare phase on the acceptor. The acceptor receives the <code>PrepareMessage</code> and evaluates if the <code>proposalId</code> is the current max <code>proposalId</code> seen so far. </p>
<p>If the <code>proposalId</code> is the max <code>proposalId</code> seen so far, it will reply back with a <code>PromiseMessage</code>. If the value is less than the current max id, it will ignore it.</p>


<p>Therefore, most of the functions will have function definitions like this:</p>


<p>With this, the algorithm's core logic becomes stateless – it doesn't really care about each machine's internal state and process. </p>
<p>We have created pure state management. This makes testing and debugging the Paxos algorithm easier. The important part here is that the <code>Action</code> method can be carried out by some other functions outside of the Paxos Algorithm to call those side effect calls.</p>
<h2 id="heading-in-closing">In Closing</h2>
<p>We just implemented a Paxos algorithm in a pure Functional style. This can be quite hard to implement because the algorithm in the paper is a stateful algorithm. You need to keep track of each state to reach a consensus.</p>
<p>Nevertheless, we take the approach to separate all algorithms into two logics – the impure functionality and core state management.</p>
<p>Separating the IO and the core state management logic in the algorithm is the biggest advantage to make the algorithm testable even in the concurrent environment. </p>
<p>Further, we make each message handling logic as stateless as possible – each call can finish without consulting any internal states of each machine or process. </p>
<p>Lastly, constructing all your algebra and all the messages that it needs at the beginning really helps shape implementing the algorithm itself. </p>
<p>The rest of the code implementation is in this GitHub <a target="_blank" href="https://github.com/edwardGunawan/Blog-Tutorial/tree/master/ScalaTutorial/paxos/src/main/scala/paxos">here</a>.</p>
<p>If you are interested to learn more about the Paxos algorithm and implementation, you can check out these resources:</p>
<ul>
<li><a target="_blank" href="https://github.com/cocagne/scala-composable-paxos/blob/master/src/main/scala/com/github/cocagne/composable_paxos/Learner.scala">scala-composable-paxos/Learner.scala at master · cocagne/scala-composable-paxos · GitHub</a></li>
<li><a target="_blank" href="https://understandingpaxos.wordpress.com/">Understanding Paxos</a></li>
<li><a target="_blank" href="https://www.scs.stanford.edu/14sp-cs240h/projects/ma.pdf">Paxos in Haskell</a></li>
</ul>
<p>Thanks for reading! If you enjoyed this post, feel free to <a target="_blank" href="https://edward-huang.com/subscribe/">subscribe</a> to my newsletter for more posts like it.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Functional Programming in JavaScript for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ By Nahla Davies Functional programming is not a new approach to coding, but it has grown in popularity in recent years. This is because, once programmers understand the basics behind the technique (and are able to write clean and reliable code using ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/functional-programming-in-javascript-for-beginners/</link>
                <guid isPermaLink="false">66d46040f855545810e9349d</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 25 Mar 2021 16:53:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/60398767a675540a2292447c.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Nahla Davies</p>
<p>Functional programming is not a new approach to coding, but it has grown in popularity in recent years.</p>
<p>This is because, once programmers understand the basics behind the technique (and are able to write clean and reliable code using it), applications written using a functional approach are much easier to work with.</p>
<p>Because of this, it’s worth gaining an understanding of functional programming once you’ve worked through this <a target="_blank" href="https://www.freecodecamp.org/news/the-complete-javascript-handbook-f26b2c71719c/">JavaScript beginners’ handbook</a>. </p>
<p>If you are frequently working with JavaScript, using this approach can save you time, and can make your code easier to work with and potentially more secure.</p>
<p>In this article, we’ll look at the basic principles of functional programming, and then outline a few of the key tools for using this approach in JavaScript.</p>
<h2 id="heading-imperative-vs-functional-programming">Imperative vs. functional programming</h2>
<p>The origins of functional programming go way back to the 1930’s with the invention of Lambda Calculus. </p>
<p>This was an approach to computation that <a target="_blank" href="https://en.wikipedia.org/wiki/Lambda_calculus">sought to define common tasks</a> and functions not as the structural manipulation of data structures (such as arrays and lists), but rather as mathematical functions performed on them. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-144.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://android.jlelse.eu/how-to-wrap-your-imperative-brain-around-functional-reactive-programming-in-rxjava-91ac89a4eccf">Image Source</a></em></p>
<p>This may sound quite abstract, especially if you are new to programming. But in fact the difference between a functional and imperative approach can be expressed quite succinctly by using an example. Take a look at these:</p>
<h3 id="heading-imperative">Imperative:</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getOdds</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">let</span> odds = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length + <span class="hljs-number">1</span>; i++) {
    <span class="hljs-keyword">if</span> (i % <span class="hljs-number">2</span> !== <span class="hljs-number">0</span>) {
      odds.push(i);
    }
  }
  <span class="hljs-keyword">return</span> odds;
}

<span class="hljs-built_in">console</span>.log(getOdds(arr)); <span class="hljs-comment">// logs [1, 3, 5, 7, 9]</span>
</code></pre>
<h3 id="heading-functional">Functional:</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getOdds2</span>(<span class="hljs-params">arr</span>)</span>{
<span class="hljs-keyword">return</span> arr.filter(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">2</span> !== <span class="hljs-number">0</span>)
}<span class="hljs-built_in">console</span>.log(getOdds2(arr))
<span class="hljs-comment">// logs [ 1, 3, 5, 7, 9 ]</span>
<span class="hljs-keyword">const</span> getOdds3 = <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr.filter(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">2</span> !== <span class="hljs-number">0</span>)<span class="hljs-built_in">console</span>.log(getOdds3(arr))
<span class="hljs-comment">// logs [ 1, 3, 5, 7, 9 ]</span>
</code></pre>
<p>As you can see, the way in which these programs work is quite different.</p>
<p>The imperative approach is to define a data structure, and then manipulate it in order to obtain the output we need. In a functional approach, we use filter functions to define a programmed function, and then invoke this as needed. </p>
<p>Of course, much of the complexity of <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-the-basic-principles-of-functional-programming-a2c2a15c84/">how functional programming works</a> is hidden from the end user, and also from the programmer if they are using a front end development framework. </p>
<p>But the advantages of using a functional approach are clear even from this example – this paradigm results in shorter code that is more easily read, understood, and audited.</p>
<h2 id="heading-why-use-functional-programming">Why use functional programming?</h2>
<p>In addition to this basic advantage, there are a number of other advantages to using functional programming. </p>
<p>Many of these stem from the simple fact that functional code is easier to read than imperatively defined code. Because a human can easily see how a functional program works, rather than having to pull apart the code in order to understand it, many aspects of testing are simplified. </p>
<h3 id="heading-functional-programming-ensures-code-integrity-with-penetration-testing">Functional Programming ensures code integrity with penetration testing</h3>
<p>Penetration testing becomes more effective where code is human readable. This makes it easier to assess the integrity of functional code.</p>
<p>According to software developer Barbara Ericson of <a target="_blank" href="https://www.clouddefense.ai/blog/penetration-testing">Cloud Defense</a>, penetration testing should always be carried out on JavaScript applications, and a functional approach can help to make this more rigorous. </p>
<p>This ease of reading also simplifies many of the other managerial processes that apply to the development of new code and applications. </p>
<p>In functional approaches, compliance processes are much easier, because programmers shouldn’t worry as much about the execution of their code. This means that the parts of a program that deal with sensitive data can be isolated and evaluated separately from the rest of a program.</p>
<h3 id="heading-functional-programming-makes-code-easier-to-read">Functional Programming makes code easier to read</h3>
<p>The advantages of functional approaches are not just limited to the assessment of code, though. They also extend to the process of developing it. </p>
<p>In fact, functional approaches build on and amplify the <a target="_blank" href="https://www.freecodecamp.org/news/the-advantages-and-disadvantages-of-javascript/">advantages and disadvantages</a> of JavaScript itself. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-145.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://itnext.io/why-are-we-creating-a-javascript-only-world-wide-web-db8c3a340b9">Image Source</a></em></p>
<p>By making code easier to read, you can bring many more staff groups into the development process, even if they don't have an extensive understanding of JavaScript.</p>
<p>This is a key tenet of the DevOps approach, one that <a target="_blank" href="https://privacycanada.net/how-to-fight-common-java-security-vulnerabilities-from-devops/">can help mitigate vulnerabilities</a> in your JavaScript code. It's also one that is facilitated by taking a functional approach to your coding.</p>
<h2 id="heading-key-tools-for-functional-programming">Key tools for functional programming</h2>
<p>There are a number of key tools and concepts that you should be aware of when it comes to actually putting functional approaches into action. Let’s take a look at them.</p>
<h3 id="heading-1-pure-and-impure-functions">1. Pure and impure functions</h3>
<p>At the most basic level, a functional approach seeks to manipulate data without mutating them. This means that a “functional function” will take data, perform some calculations, and return a result (and all without re-writing any part of the data structure itself). </p>
<p>Functions that work in this way are called “pure” functions, and those that do not are called “impure”.</p>
<pre><code class="lang-js">
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getSquare</span>(<span class="hljs-params">items</span>) </span>{
  <span class="hljs-keyword">var</span> len = items.length;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; len; i++) {
    items[i] = items[i] * items[i];
  }
  <span class="hljs-keyword">return</span> items;
}
</code></pre>
<p>The general idea here is to leave the data you are working with completely untouched. </p>
<p>If you want to merge two arrays, you should not utilize the <code>Array.prototype.push()</code> strategy (which will overwrite the original data). Instead, use the <code>Array.prototype.concat()</code> function, which will create a new, “working” array for you to work with.</p>
<h3 id="heading-2-anonymous-functions">2. Anonymous functions</h3>
<p>Anonymous functions are also an important part of functional programming, and one that has its roots in Lambda Calculus. </p>
<p>Anonymous functions, as their name suggests, do not have an explicitly defined name. Instead, they are functions that are assigned to variables, and invoked via them. </p>
<pre><code class="lang-js"> alert((<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">x</span>) </span>{
    <span class="hljs-keyword">return</span> !(x &gt; <span class="hljs-number">1</span>)
      ? <span class="hljs-number">1</span>
      : <span class="hljs-built_in">arguments</span>.callee(x - <span class="hljs-number">1</span>) * x;
  })(<span class="hljs-number">20</span>));
</code></pre>
<p>The advantage of doing this is that as long as you are able to keep track of which functions are assigned to which variables, they can be invoked very easily, and passed from one module to another with nothing more than a variable call. This gives you a powerful, flexible new way of working with functions.</p>
<h3 id="heading-3-recursive-functions">3. Recursive functions</h3>
<p>The use of recursive functions is another mark of functional programming. Though the general idea of recursion will be familiar to even beginner programmers, functional programming takes the idea even further by defining functions that call themselves. </p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">countDown</span>(<span class="hljs-params">fromNumber</span>) </span>{
    <span class="hljs-built_in">console</span>.log(fromNumber);

    <span class="hljs-keyword">let</span> nextNumber = fromNumber - <span class="hljs-number">1</span>;

    <span class="hljs-keyword">if</span> (nextNumber &gt; <span class="hljs-number">0</span>) {
        countDown(nextNumber);
    }
}
countDown(<span class="hljs-number">3</span>);
</code></pre>
<p>This makes the implementation of recursion much simpler – largely because programmers don’t need to use loops to do this. </p>
<p>However, it also comes with dangers. Specifically, having a function call itself makes it much easier for infinite loops to be accidentally created, and so take care to underpin every recursive function with a rigorous way of stopping execution.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Though these three concepts are typical of functional programming, in truth the range of ways in which the paradigm can be applied means that it is more of a philosophy than a set of well-designed tools and processes. </p>
<p>Take a few steps into the exciting world of functional programming, and you’ll start to see its influence everywhere. In fact, it informs many of the <a target="_blank" href="https://www.freecodecamp.org/news/what-is-javascript/">most common JavaScript practices</a> in use today.</p>
<p>In other words, although functional programming appears simple on the surface, it has profound consequences on the way that you code. This is why it’s worth learning, even if you don’t use it all the time.  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Functional Programming? A Beginner's JavaScript Guide ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is a multi-paradigm language and can be written following different programming paradigms. A programming paradigm is essentially a bunch of rules that you follow when writing code. These paradigms exist because they solve problems that pro... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/functional-programming-in-javascript/</link>
                <guid isPermaLink="false">66bc55d7e35f27b353950758</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kealan Parr ]]>
                </dc:creator>
                <pubDate>Tue, 17 Nov 2020 21:06:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/11/Functional-code.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is a multi-paradigm language and can be written following different programming paradigms. A programming paradigm is essentially a bunch of rules that you follow when writing code.</p>
<p>These paradigms exist because they solve problems that programmers face, and they have their own rules and instructions to help you write better code.</p>
<p>Each paradigm helps you solve a specific problem. So it's helpful to have an overview of each of them. We'll cover functional programming here.</p>
<p>At the end of this article, there are some resources you can use to go further if you enjoyed this introduction. </p>
<p>There's also a GitHub glossary that'll help you decode some of the jargon that functional programming uses. </p>
<p>Lastly, you'll find a place to get your hands dirty coding with practical examples and a GitHub repo full of resources you can use to learn more. So let's dive in.</p>
<h2 id="heading-declarative-vs-imperative-programming-paradigms">Declarative vs Imperative Programming Paradigms</h2>
<p>One example of these paradigms I talked about at the beginning is object-orientated programming. Another is functional programming.</p>
<p>So what exactly is functional programming? </p>
<p>Functional programming is a sub-paradigm of the <strong>Declarative programming</strong> paradigm, with its own rules to follow when writing code.</p>
<h3 id="heading-what-is-the-declarative-programming-paradigm">What is the declarative programming paradigm?</h3>
<p>If you're coding in a language that follows the declarative paradigm, you write code that specifies <strong>what you want to do, without saying how.</strong></p>
<p>A super simple example of this is either SQL or HTML:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> customers
</code></pre>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>In the above code examples, you aren't implementing the <code>SELECT</code> or how to render a <code>div</code>. You are just telling the computer <em>what</em> to do, without the <em>how</em>.</p>
<p>From this paradigm, there are sub-paradigms such as <strong>Functional programming.</strong> More on that below.</p>
<h3 id="heading-what-is-the-imperative-programming-paradigm">What is the imperative programming paradigm?</h3>
<p>If you're coding in a language that follows the imperative/procedural paradigm, you write code that tells <strong>how to do something.</strong></p>
<p>For example, if you do something like below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) {
     increment += arr[i];
}
</code></pre>
<p>You are telling the computer exactly what to do. Iterate through the array called <code>arr</code>, and then <code>increment</code> each of the items in the array.</p>
<h3 id="heading-declarative-vs-imperative-programming">Declarative vs Imperative programming</h3>
<p>You can write JavaScript in the <strong>Declarative paradigm</strong> or the <strong>Imperative paradigm.</strong> This is what people mean when they say it's a multi-paradigm language. It's just that functional code follows the <strong>Declarative paradigm</strong>.</p>
<p>If it helps you remember, an example of a declarative command would be to ask the computer to make you a cup of tea (I don't care how you do it, just bring me some tea).</p>
<p>Whilst imperatively, you would have to say:</p>
<ul>
<li>Go to the kitchen.</li>
<li>If there is a kettle in the room, and it has enough water for a cup of tea, turn on the kettle.</li>
<li>If there is a kettle in the room, and it doesn't have enough water for a cup of tea, fill the kettle with enough water for a cup of tea, then turn on the kettle.</li>
<li><em>And so on</em></li>
</ul>
<h3 id="heading-so-what-is-functional-programming">So what is Functional Programming?</h3>
<p>So what does this mean for functional code?</p>
<p>Because it's a sub-paradigm from the <strong>Declarative paradigm</strong>, this affects the way you write functional code. It generally leads to less code, because JavaScript already has a lot of the in-built functions you commonly need. This is one reason people like functional code. </p>
<p>It also allows you to abstract away a lot (you don't have to understand in depth how something gets done), you just call a function that does it for you.</p>
<p>And what are the rules that lead to functional code?</p>
<p>Functional programming can be simply explained by following these 2 laws in your code:</p>
<ol>
<li><strong>You architect your software out of pure, isolated functions</strong></li>
<li><strong>You avoid mutability and side-effects</strong></li>
</ol>
<p>Let's dig into that.</p>
<h2 id="heading-1-architect-your-software-out-of-pure-isolated-functions">1. Architect your software out of pure, isolated functions</h2>
<p>Let's start at the beginning, </p>
<p>Functional code makes heavy use of a few things:</p>
<h3 id="heading-pure-functions">Pure functions</h3>
<p>The same input always gives the same output (<strong>idempotence</strong>), and has no side effects. </p>
<p>An <strong>idempotent function</strong>, is one that, when you reapply the results to that function again, doesn't produce a different result.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/// Example of some Math.abs uses</span>
<span class="hljs-built_in">Math</span>.abs(<span class="hljs-string">'-1'</span>);     <span class="hljs-comment">// 1</span>
<span class="hljs-built_in">Math</span>.abs(<span class="hljs-number">-1</span>);       <span class="hljs-comment">// 1</span>
<span class="hljs-built_in">Math</span>.abs(<span class="hljs-literal">null</span>);     <span class="hljs-comment">// 0</span>


<span class="hljs-built_in">Math</span>.abs(<span class="hljs-built_in">Math</span>.abs(<span class="hljs-built_in">Math</span>.abs(<span class="hljs-string">'-1'</span>)));           <span class="hljs-comment">// Still returns 1</span>
<span class="hljs-built_in">Math</span>.abs(<span class="hljs-built_in">Math</span>.abs(<span class="hljs-built_in">Math</span>.abs(<span class="hljs-built_in">Math</span>.abs(<span class="hljs-string">'-1'</span>)))); <span class="hljs-comment">// Still returns 1</span>
</code></pre>
<p>Side effects are when your code interacts with (reads or writes to) external mutable state. </p>
<p>External mutable state is literally anything outside the function that would change the data in your program. Set a function? Set a Boolean on an object? Delete properties on an object? All changes to state outside your function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setAvailability</span>(<span class="hljs-params"></span>)</span>{
    available = <span class="hljs-literal">true</span>;
}
</code></pre>
<h3 id="heading-isolated-functions">Isolated functions</h3>
<p>There is no dependence on the state of the program, which includes global variables that are subject to change. </p>
<p>We will discuss this further, but anything that you need should be passed into the function as an argument. This makes your dependencies (things that the function needs to do its job) much clearer to see, and more discoverable.</p>
<p>Ok, so why do you do things this way?</p>
<p>I know this seems like lots of restrictions that make your code unnecessarily hard. But they aren't restrictions, they are guidelines that try to stop you from falling into patterns that commonly lead to bugs.</p>
<p>When you aren't changing your code execution, forking your code with <code>if</code> 's based on <code>Boolean</code>'s state, being set by multiple places in your code, you make the code more predictable and it's easier to reason about what's happening.</p>
<p>When you follow the functional paradigm, you'll find that the execution order of your code doesn't matter as much. </p>
<p>This has quite a few benefits – one being, for example, that to replicate a bug you don't need to know exactly what each <code>Boolean</code> and <code>Object</code>'s state was before you run your functions. As long as you have a call stack (you know what function is running/has run before you) it can replicate the bugs, and solve them more easily.</p>
<h3 id="heading-reusability-through-higher-order-functions">Reusability through Higher order functions</h3>
<p>Functions that can be assigned to a variable, passed into another function, or returned from another function just like any other normal value, are called <strong>first class functions</strong>. </p>
<p>In JavaScript, all functions are first class functions. Functions that have a first class status allow us to create <strong>higher order functions</strong>.</p>
<p>A <strong>higher order function</strong> is a function that either take a function as an argument, returns a function, or both! You can use higher order functions to stop repeating yourself in your code.</p>
<p>Something like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Here's a non-functional example</span>
<span class="hljs-keyword">const</span> ages = [<span class="hljs-number">12</span>,<span class="hljs-number">32</span>,<span class="hljs-number">32</span>,<span class="hljs-number">53</span>]
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i=<span class="hljs-number">0</span>; i &lt; ages.length; i++) {
    finalAge += ages[i];
}

<span class="hljs-comment">// Here's a functional example</span>
<span class="hljs-keyword">const</span> ages = [<span class="hljs-number">12</span>,<span class="hljs-number">32</span>,<span class="hljs-number">32</span>,<span class="hljs-number">53</span>]
<span class="hljs-keyword">const</span> totalAge = ages.reduce( <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">firstAge, secondAge</span>)</span>{
    <span class="hljs-keyword">return</span> firstAge + secondAge;
})
</code></pre>
<p>The in-built JavaScript <code>Array</code> functions <code>.map</code>, <code>.reduce</code>, and <code>.filter</code> all accept a function. They are excellent examples of <strong>higher order functions,</strong> as they iterate over an array and call the function they received for each item in the array.</p>
<p>So you could do:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Here's an example of each</span>
<span class="hljs-keyword">const</span> array = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-keyword">const</span> mappedArray = array.map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">element</span>)</span>{
    <span class="hljs-keyword">return</span> element + <span class="hljs-number">1</span>;
});
<span class="hljs-comment">// mappedArray is [2, 3, 4]</span>

<span class="hljs-keyword">const</span> reduced = array.reduce(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">firstElement, secondElement</span>)</span>{
    <span class="hljs-keyword">return</span> firstElement + secondElement;
});
<span class="hljs-comment">// reduced is 6</span>

<span class="hljs-keyword">const</span> filteredArray = array.filter(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">element</span>)</span>{
    <span class="hljs-keyword">return</span> element !== <span class="hljs-number">1</span>;
});
<span class="hljs-comment">// filteredArray is [2, 3]</span>
</code></pre>
<p>Passing the results of functions into other functions, or even passing the functions themselves, in is extremely common in functional code. I included this brief explanation because of how often it is used.</p>
<p>These functions are also often used because they don't change the underlying function (no state change) but operate on a copy of the <code>array</code>.</p>
<h2 id="heading-2-avoid-mutability-and-side-effects">2. Avoid mutability and side-effects</h2>
<p>The second rule is to avoid mutability – we touched on this briefly earlier, when we talked about limiting changes to external mutable state – and side effects.</p>
<p>But here we'll expand further. Basically, it boils down to this: don't change things! Once you've made it, it is <strong>immutable</strong> (unchanging over time).</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> ages = [<span class="hljs-number">12</span>,<span class="hljs-number">32</span>,<span class="hljs-number">32</span>,<span class="hljs-number">53</span>]
ages[<span class="hljs-number">1</span>] = <span class="hljs-number">12</span>;  <span class="hljs-comment">// no!</span>
ages = [];     <span class="hljs-comment">// no!</span>
ages.push(<span class="hljs-string">"2"</span>) <span class="hljs-comment">// no!</span>
</code></pre>
<p>If something has to change for your data structures, make changes to a copy.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ages = [<span class="hljs-number">12</span>,<span class="hljs-number">32</span>,<span class="hljs-number">32</span>,<span class="hljs-number">53</span>]
<span class="hljs-keyword">const</span> newAges = ages.map(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">age</span>)</span>{
    <span class="hljs-keyword">if</span> (age == <span class="hljs-number">12</span>) { <span class="hljs-keyword">return</span> <span class="hljs-number">20</span>; }
    <span class="hljs-keyword">else</span> { <span class="hljs-keyword">return</span> age; }
})
</code></pre>
<p>Can you see I made a copy with my necessary changes?</p>
<p>This element is repeated over and over again. Don't change state! </p>
<p>If we follow that rule, we will make heavy use of <code>const</code> so we know things wont change. But it has to go further than that. How about the below?</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> changingObject = {
    <span class="hljs-attr">willChange</span>: <span class="hljs-number">10</span>
}

changingObject.willChange = <span class="hljs-number">10</span>;  <span class="hljs-comment">// no!</span>
<span class="hljs-keyword">delete</span> obj.willChange            <span class="hljs-comment">// no!</span>
</code></pre>
<p>The properties of <code>changingObject</code> should be locked down completely. <code>const</code> will only protect you from initializing over the variable.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = <span class="hljs-built_in">Object</span>.freeze({
    <span class="hljs-attr">cantChange</span>: <span class="hljs-string">'Locked'</span> }) <span class="hljs-comment">// The `freeze` function enforces immutability.</span>

obj.cantChange = <span class="hljs-number">0</span>      <span class="hljs-comment">// Doesn't change the obj!</span>
<span class="hljs-keyword">delete</span> obj.cantChange   <span class="hljs-comment">// Doesn't change the obj!</span>
obj.addProp = <span class="hljs-string">"Gotcha!"</span> <span class="hljs-comment">// Doesn't change the obj!</span>
</code></pre>
<p>If we can't change the state of global variables, then we need to ensure:</p>
<ul>
<li>We declare function arguments – any computation inside a function depends only on the arguments, and not on any global object or variable.</li>
<li>We don't alter a variable or object – create new variables and objects and return them if need be from a function.</li>
</ul>
<h3 id="heading-make-your-code-referentially-transparent">Make your code referentially transparent</h3>
<p>When you follow the rule of never changing state, your code becomes <strong>referentially transparent</strong>. That is, your function calls can be replaced with the values that they represent without affecting the result.</p>
<p>As a simple example of checking if your code is <strong>referentially transparent,</strong> look at the below code snippet:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greetAuthor = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hi Kealan'</span>
}
</code></pre>
<p>You should be able to just swap that function call with the <code>string</code> it returns, and have no problems. </p>
<p>Functional programming with referentially transparent expressions makes you start to think about your code differently if you're used to <strong>object orientation</strong>.</p>
<p>But why?</p>
<p>Because instead of objects and mutable state in your code, you start to have pure functions, with no state change. You understand very clearly what you are expecting your function to return (as it never changes, when normally it might return different data types depending on state outside the function).</p>
<p>It can help you understand the flow better, understand what a function is doing just by skimming it, and be more rigorous with each function's responsibilities to come up with better decoupled systems.</p>
<p>You can learn more about referential transparency <a target="_blank" href="https://medium.com/@olxc/referential-transparency-93352c2dd713">here</a>.</p>
<h3 id="heading-dont-iterate">Don't iterate</h3>
<p>Hopefully, if you've paid attention so far, you see we aren't changing state. So just to be clear <code>for</code> loops go out the window:</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) {
    total += arr[i];
}
</code></pre>
<p>Because we are changing a variable's state there. Use the <code>map</code> higher order function instead.</p>
<h2 id="heading-more-features-of-functional-programming">More Features of Functional Programming</h2>
<p>I hope at this point you have a good overview of what functional code is and isn't. But there's some final concepts used heavily in functional code that we have to cover. </p>
<p>In all the functional code I have read, these concepts and tools are used the most, and we have to cover them to get our foundational knowledge.</p>
<p>So here we go.</p>
<h2 id="heading-recursion-in-functional-programming">Recursion in Functional Programming</h2>
<p>It's possible in JavaScript to call a function from the function itself.</p>
<p>So what we could always do:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">recurse</span>(<span class="hljs-params"></span>)</span>{
    recurse();
}
</code></pre>
<p>The problem with this is that it isn't useful. It will run eventually until it crashes your browser. But the idea of recursion is a function calling itself from its function body. So let's see a more useful example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">recurse</span>(<span class="hljs-params">start, end</span>)</span>{
    <span class="hljs-keyword">if</span> (start == end) {
        <span class="hljs-built_in">console</span>.log(end)
        <span class="hljs-keyword">return</span>;
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">console</span>.log(start)
        <span class="hljs-keyword">return</span> recurse(start+<span class="hljs-number">1</span>, end)
    }
}

recurse(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>);
<span class="hljs-comment">// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10</span>
</code></pre>
<p>This code snippet will count from the <code>start</code> argument to the <code>end</code> argument. And it does so by calling its own function again.</p>
<p>So the order of this will look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/image-135.png" alt="Image" width="600" height="400" loading="lazy">
<em>A call stack example for this recursive function.</em></p>
<p>Add a debugger inside the if blocks to follow this if it doesn't make sense to you. Recursion is one tool you can use to iterate in functional programming.</p>
<p>What makes the first example and the second example different? The second one has what we call <strong>"a base case"</strong>. A base case lets the function eventually stop calling into itself infinitely. When <code>start</code> is equal to <code>end</code> we can stop recursing. As we know we have counted to the very end of our loop.</p>
<p>But each call of the functions is calling into its own function again, and adding on to the function argument.</p>
<p>The code example I just included for the counting example isn't a <strong>pure function</strong>. Why is that?</p>
<p>Because the <code>console</code> is state! And we logged <code>string</code>'s to it. </p>
<p>This has been a brief introduction to recursion, but feel free to go here to learn more <a target="_blank" href="https://javascript.info/recursion">here</a>.</p>
<h3 id="heading-why-use-recursion">Why use recursion?</h3>
<p>Recursion allows us to stop mutating state variables, for one.</p>
<p>There are also certain data structures (tree structures) that are more efficient when solved with recursion. They generally require less code, so some coders like the readability of recursion. </p>
<h2 id="heading-currying-in-functional-programming">Currying in Functional Programming</h2>
<p>Currying is another tool used heavily in functional code. The <strong>arity</strong> of a function refers to how many arguments it receives.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Let's talk arity</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">arity2</span>(<span class="hljs-params">arg1, arg2</span>)</span>{}             <span class="hljs-comment">// Function has an arity of 2</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">arity0</span>(<span class="hljs-params"></span>)</span>{}                       <span class="hljs-comment">// Function has an arity of 0</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">arity2</span>(<span class="hljs-params">arg1, arg2, arg3, arg4</span>)</span>{} <span class="hljs-comment">// Function has an arity of 4</span>
</code></pre>
<p><strong>Currying</strong> a function turns a function that has an arity of more than 1, to 1. It does this by returning an inner function to take the next argument. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">firstNum, secondNum</span>)</span>{
    <span class="hljs-keyword">return</span> firstNum + secondNum;
}

<span class="hljs-comment">// Lets curry this function</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">curryAdd</span>(<span class="hljs-params">firstNum</span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">secondNum</span>)</span>{
            <span class="hljs-keyword">return</span> firstNum + secondNum;
    }
}
</code></pre>
<p>Essentially, it restructures a function so it takes one argument, but it then returns another function to take the next argument, as many times as it needs to. </p>
<h3 id="heading-why-use-currying">Why use currying?</h3>
<p>The big benefit of currying is when you need to re-use the same function multiple times but only change one (or fewer) of the parameters. So you can save the first function call, something like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">curryAdd</span>(<span class="hljs-params">firstNum</span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">secondNum</span>)</span>{
            <span class="hljs-keyword">return</span> firstNum + secondNum;
    }
}

<span class="hljs-keyword">let</span> add10 = curryAdd(<span class="hljs-number">10</span>);
add10(<span class="hljs-number">2</span>); <span class="hljs-comment">// Returns 12</span>

<span class="hljs-keyword">let</span> add20 = curryAdd(<span class="hljs-number">20</span>);
add20(<span class="hljs-number">2</span>); <span class="hljs-comment">// Returns 22</span>
</code></pre>
<p>Currying can also make your code easier to refactor. You don't have to change multiple places where you are passing in the wrong function arguments – just the one place, where you bound the first function call to the wrong argument.</p>
<p>It's also helpful if you can't supply all the arguments to a function at one time. You can just return the first function to call the inner function when you have all the arguments later. </p>
<h2 id="heading-partial-application-in-functional-programming">Partial application in Functional Programming</h2>
<p>Similarly, partial application means that you apply a few arguments to a function at a time and return another function that is applied to more arguments. Here's the best example I found from the MDN docs:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> <span class="hljs-built_in">module</span> = {
  <span class="hljs-attr">height</span>: <span class="hljs-number">42</span>,
  <span class="hljs-attr">getComputedHeight</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">height</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.height + height;
  }
};

<span class="hljs-keyword">const</span> unboundGetComputedHeight = <span class="hljs-built_in">module</span>.getComputedHeight;
<span class="hljs-built_in">console</span>.log(unboundGetComputedHeight(<span class="hljs-number">32</span>)); <span class="hljs-comment">// The function gets invoked at the global scope</span>
<span class="hljs-comment">// outputs: NaN</span>
<span class="hljs-comment">// Outputs NaN as this.height is undefined (on scope of window) so does </span>
<span class="hljs-comment">// undefined + 32 which returns NaN</span>

<span class="hljs-keyword">const</span> boundGetComputedHeight = unboundGetComputedHeight.bind(<span class="hljs-built_in">module</span>);
<span class="hljs-built_in">console</span>.log(boundGetComputedHeight(<span class="hljs-number">32</span>));
<span class="hljs-comment">// expected output: 74</span>
</code></pre>
<p><code>bind</code> is the best example of a partial application. Why?</p>
<p>Because we return an inner function that gets assigned to <code>boundGetComputedHeight</code> that gets called, with the <code>this</code> scope correctly set up and a new argument passed in later. We didn't assign all the arguments at once, but instead we returned a function to accept the rest of the arguments.</p>
<h3 id="heading-why-use-partial-application">Why use partial application?</h3>
<p>You can use partial application whenever you can't pass all your arguments at once, but can return <code>function</code>s from higher order functions to deal with the rest of the arguments.</p>
<h2 id="heading-function-composition-in-functional-programming">Function composition in Functional Programming</h2>
<p>The final topic that I think is fundamental to functional code is <strong>function composition</strong>.</p>
<p><strong>Function composition</strong> allows us to take two or more functions and turn them into one function that does exactly what the two functions (or more) do.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// If we have these two functions</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add10</span>(<span class="hljs-params">num</span>) </span>{
    <span class="hljs-keyword">return</span> num + <span class="hljs-number">10</span>;
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add100</span>(<span class="hljs-params">num</span>) </span>{
    <span class="hljs-keyword">return</span> num + <span class="hljs-number">100</span>;
}

<span class="hljs-comment">// We can compose these two down to =&gt;</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">composed</span>(<span class="hljs-params">num</span>)</span>{
    <span class="hljs-keyword">return</span> add10(add100(num));
}

composed(<span class="hljs-number">1</span>) <span class="hljs-comment">// Returns 111</span>
</code></pre>
<p>You can take this further and create functions to compose any number of multiple arity functions together if you need that for your use case.</p>
<h3 id="heading-why-use-function-composition">Why use function composition?</h3>
<p>Composition allows you to structure your code out of re-usable functions, to stop repeating yourself. You can start to treat functions like small building blocks you can combine together to achieve a more complicated output. </p>
<p>These then become the "units" or the computation power in your programs. They're lots of small functions that work generically, all composed into larger functions to do the "real" work. </p>
<p>It's a powerful way of architecting your code, and keeps you from creating huge functions copied and pasted with tiny differences between them. </p>
<p>It can also help you test when your code is not tightly coupled. And it makes your code more reusable. You can just change the composition of your functions or add more tiny functions into the composition, rather than having all the code copied and pasted all over the codebase (for when you need it to do something similar but not quite the same as another function).</p>
<p>The example below is made trivial to help you understand, but I hope you see the power of <strong>function composition.</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">/// So here's an example where we have to copy and paste it</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add50</span>(<span class="hljs-params">num</span>) </span>{
    <span class="hljs-keyword">return</span> num + <span class="hljs-number">50</span>;
}

<span class="hljs-comment">// Ok. Now we need to add 30. But we still ALSO need elsewhere to add 50 still</span>
<span class="hljs-comment">// So we need a new function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add30</span>(<span class="hljs-params">num</span>)</span>{
    <span class="hljs-keyword">return</span> num + <span class="hljs-number">30</span>;
}

<span class="hljs-comment">// Ugh, business change again</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add20</span>(<span class="hljs-params">num</span>)</span>{
    <span class="hljs-keyword">return</span> num + <span class="hljs-number">20</span>;
}

<span class="hljs-comment">// Everytime we need to change the function ever so slightly. We need a new function</span>

<span class="hljs-comment">//Let's use composition</span>

<span class="hljs-comment">// Our small, reusable pure function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add10</span>(<span class="hljs-params">num</span>)</span>{
    <span class="hljs-keyword">return</span> num + <span class="hljs-number">10</span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add50Composed</span>(<span class="hljs-params">num</span>)</span>{
    <span class="hljs-keyword">return</span> add10(add10(add10(add10(addNum(num)))));
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add30Composed</span>(<span class="hljs-params">num</span>)</span>{
    <span class="hljs-keyword">return</span> add10(add10(add10(num)));
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add20Composed</span>(<span class="hljs-params">num</span>)</span>{
    <span class="hljs-keyword">return</span> add10(add10(num));
}
</code></pre>
<p>Do you see how we composed new functions out of smaller, pure functions?</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article covered a lot. But I hope it has explained functional code simply, along with some of the repeating patterns you will see over and over again, in functional and even non-functional code.</p>
<p>Functional code isn't necessarily the best, and neither is object orientated code. Functional code is generally used for more math-based problems like data analysis. It's also very useful for high-availability real-time systems, like stuff written in Erlang (a functional language). But it genuinely does depend problem to problem.</p>
<p>I post my articles on <a target="_blank" href="https://twitter.com/kealanparr">Twitter</a>. If you enjoyed this article you can read more there.</p>
<h2 id="heading-how-to-learn-more">How to learn more</h2>
<p>Start <a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming">here</a>, with freeCodeCamp's introduction to functional programming with JavaScript.</p>
<p>Look <a target="_blank" href="https://github.com/xgrommx/awesome-functional-programming#javascript">here</a> for some libraries you can include and play around with, to really master functional programming.</p>
<p>Peruse <a target="_blank" href="https://github.com/leandrotk/functional-programming-learning-path">this</a> good overview of lots of functional concepts.</p>
<p>Finally, <a target="_blank" href="https://github.com/hemanth/functional-programming-jargon">here's</a> an excellent jargon-busting glossary of functional terms.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Imperative vs Declarative Programming – the Difference Explained in Plain English ]]>
                </title>
                <description>
                    <![CDATA[ By Mike Zetlow As a coding instructor, it’s my duty to send programmers out into the world thinking in new ways. A major shift in thinking occurs when we switch from imperative to declarative programming. Once my students have learned basic JavaScrip... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/imperative-vs-declarative-programming-difference/</link>
                <guid isPermaLink="false">66d4603f677cb8c6c15f3161</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 08 Oct 2020 18:32:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/10/imperative-vs-declarative-programming-difference.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Mike Zetlow</p>
<p>As a coding instructor, it’s my duty to send programmers out into the world thinking in new ways. A major shift in thinking occurs when we switch from imperative to declarative programming.</p>
<p>Once my students have learned basic JavaScript, we go over functional programming and the array methods used in a declarative coding style. This is where their brains start to pop and sizzle and melt like marshmallows over a fire.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/marshmellows-on-grill-crop-1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-what-is-imperative-programming">What is Imperative Programming?</h2>
<p>As a beginner, you've probably mostly coded in an imperative style: you give the computer a set of instructions to follow and the computer does what you want in an easy-to-follow sequence.</p>
<p>Imagine we have a list of the world’s most commonly-used passwords:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> passwords = [
   <span class="hljs-string">"123456"</span>,
   <span class="hljs-string">"password"</span>,
   <span class="hljs-string">"admin"</span>,
   <span class="hljs-string">"freecodecamp"</span>,
   <span class="hljs-string">"mypassword123"</span>,
];
</code></pre>
<p>Our app is going to check the user’s password on sign up and not allow them to create a password that is from this list.</p>
<p>But before we do that, we want to refine this list. We already have code that doesn’t allow the user to sign up with a password less than 9 characters long. So we can reduce this list to just passwords that are 9 characters or more to speed up our check.</p>
<p>Imperatively, we would write:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// using the passwords constant from above</span>

<span class="hljs-keyword">let</span> longPasswords = [];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; passwords.length; i++) {
   <span class="hljs-keyword">const</span> password = passwords[i];
   <span class="hljs-keyword">if</span> (password.length &gt;= <span class="hljs-number">9</span>) {
      longPasswords.push(password);
   }
}

<span class="hljs-built_in">console</span>.log(longPasswords); <span class="hljs-comment">// logs ["freecodecamp", "mypassword123"];</span>
</code></pre>
<ol>
<li>We create an empty list called <code>longPasswords</code>.</li>
<li>Then we write a loop that will run as many times as there are passwords in the original <code>passwords</code> list.</li>
<li>Then we get the password at the index of the loop iteration we are presently on.</li>
<li>Then we check if that password is greater than or equal to 9 characters long.</li>
<li>If it is, we put it into the <code>longPasswords</code> list.</li>
</ol>
<p>One of imperative programming’s strengths is the fact that it is easy to reason about. Like a computer, we can follow along step by step.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/steps-crop.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-what-is-declarative-programming">What is Declarative Programming?</h2>
<p>But there's another way of thinking about coding – as a process of constantly defining what things are. This is referred to as declarative programming.</p>
<p>Imperative and declarative programming achieve the same goals. They are just different ways of thinking about code. They have their benefits and drawbacks and there are times to use both.</p>
<p>Though imperative programming is easier to reason about for beginners, declarative programming allows us to write more readable code that reflects what exactly we want to see. Combined with <a target="_blank" href="https://github.com/10xcodecamp/javascript-conventions-and-code-style">good variable names</a>, it can be a powerful tool.</p>
<p>So instead of giving the computer step by step instructions, we declare what it is we want and we assign this to the result of some process.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// using the passwords constant from above</span>

<span class="hljs-keyword">const</span> longPasswords = passwords.filter(<span class="hljs-function"><span class="hljs-params">password</span> =&gt;</span> password.length &gt;= <span class="hljs-number">9</span>);

<span class="hljs-built_in">console</span>.log(longPasswords); <span class="hljs-comment">// logs ["freecodecamp", "mypassword123"];</span>
</code></pre>
<p>The list of <code>longPasswords</code> is defined (or declared) as the list of <code>passwords</code> filtered for only passwords greater than or equal to 9 characters.</p>
<p>The functional programming methods in JavaScript enable us to cleanly declare things.</p>
<ul>
<li><strong>This is a list of passwords.</strong></li>
<li><strong>This is a list of only long passwords.</strong> (After running <code>filter</code>.)</li>
<li><strong>This is a list of passwords with ids.</strong> (After running <code>map</code>.)</li>
<li><strong>This is a single password.</strong> (After running <code>find</code>.)</li>
</ul>
<p>One of declarative programming’s strengths is that it forces us to ask what we want first. It is in the naming of these new things that our code becomes expressive and explicit. </p>
<p>And when our fellow developers come along and look at our code, they can find bugs more easily:</p>
<p>“You call this variable ‘index’ which makes me expect a number, but I see it is the result of <code>filter</code> which returns an array. What’s up with that?”</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/women-coding-at-home-crop.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I encourage learners to write declarative code as often as possible, constantly defining (and refactoring to redefine) what things are. </p>
<p>Rather than hold an entire imperative process in your head, you can hold a more tangible <strong>thing</strong> in your head with a clear definition.</p>
<p><em>Mike Zetlow is the Lead Instructor at</em> <a target="_blank" href="https://www.10xcodecamp.com/"><em>10x Code Camp</em></a><em>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Functional Programming in JavaScript Explained in Plain English ]]>
                </title>
                <description>
                    <![CDATA[ By Joel P. Mugalu One of the hardest things you have to do in programming is control complexity. Without careful consideration, a program's size and complexity can grow to the point where it confuses even the creator of the program. In fact, as one a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/functional-programming-in-javascript-explained-in-plain-english/</link>
                <guid isPermaLink="false">66d45e01182810487e0ce123</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 05 Oct 2020 16:45:41 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/09/blog1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Joel P. Mugalu</p>
<p>One of the hardest things you have to do in programming is control complexity. Without careful consideration, a program's size and complexity can grow to the point where it confuses even the creator of the program.</p>
<p>In fact, as one author put it:</p>
<blockquote>
<p>"The art of programming is the skill of controlling complexity" - Marijn Haverbeke</p>
</blockquote>
<p>In this article we will break down a major programming concept. This programming concept can help you keep complexity under control and write better programs.</p>
<p>By the end of this article, you will know what functional programming is, the types of functions there are, the principles of functional programming, and have a deeper understanding of Higher Order functions.</p>
<p>I assume that you already have pre-existing knowledge of the basics of functions. The fundamental concepts of functions will not be covered in this article.</p>
<p>If you want a quick review of functions in JavaScript, then I've written a detailed article <a target="_blank" href="https://dev.to/codingknite/javascript-functions-broken-down-4fgh">here</a>.</p>
<h2 id="heading-what-is-functional-programming">What is Functional Programming?</h2>
<p>Functional programming is a programming paradigm or style of programming that relies heavily on the use of pure and isolated functions.</p>
<p>Just as you might have guessed from the name, the use of functions is the main component of functional programming. But, merely using functions doesn't translate to functional programming.</p>
<p>In functional programming, we use pure functions, which are functions that don't have side effects. I will explain what all of this means.</p>
<p>Before diving deeper into the article, let us understand some of the terminology and types of functions there are.</p>
<h2 id="heading-types-of-functions">Types of Functions</h2>
<p>There are four main types of functions.</p>
<h3 id="heading-first-class-functions">First Class Functions</h3>
<p>In JavaScript all functions are first class functions. That means they can be treated like any other variable.</p>
<p>First class functions are functions that can be assigned as values to variables, returned from other functions, and passed as arguments to other functions.</p>
<p>Consider this example of a function passed to a variable:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> helloWorld = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello, World"</span>); <span class="hljs-comment">// Hello, World</span>
};
helloWorld();
</code></pre>
<h3 id="heading-callback-functions">Callback Functions</h3>
<p>Callback functions are functions that are passed into other functions as arguments and are called by the function in which they are passed.</p>
<p>Simply, callback functions are functions that we write as arguments in other functions. We can't invoke callback functions. They are invoked when the main function in which they were passed as arguments is called.</p>
<p>Let's look at an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> testValue = <span class="hljs-function">(<span class="hljs-params">value, test</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (test(value)) {
        <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${value}</span> passed the test`</span>;
    } <span class="hljs-keyword">else</span> 
        <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${value}</span> did not pass the test`</span>;
};
<span class="hljs-keyword">const</span> checkString = testValue(<span class="hljs-string">'Twitter'</span>,  <span class="hljs-function"><span class="hljs-params">string</span>  =&gt;</span>  <span class="hljs-keyword">typeof</span>  string === <span class="hljs-string">'string'</span>);
checkString; <span class="hljs-comment">// Twitter passed the test</span>
</code></pre>
<p><code>testValue</code> is a function that accepts a  value and a callback function <code>test</code>  which returns "value passed the test" if the value returns true when passed into the callback function.</p>
<p>In this case, the callback function is the second argument we passed into the <code>testValue</code> function. It is invoked when the <code>testValue</code> function is called.</p>
<h3 id="heading-higher-order-functions">Higher Order Functions</h3>
<p>Higher order functions are functions that receive other functions as arguments or return a function.</p>
<p>In this article, am going to further elaborate on higher order functions and why they are such a powerful provision. For now, all you need to know is that these types of functions receive other functions as arguments or return functions.</p>
<h3 id="heading-asynchronous-functions">Asynchronous Functions</h3>
<p>Asynchronous functions are functions that don't have a name and cannot be reused. These functions are normally written when we need to carry out something once and in only one place.</p>
<p>A perfect example of an asynchronous function is what we wrote earlier in the article.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> checkString = testValue(<span class="hljs-string">'Twitter'</span>,  <span class="hljs-function"><span class="hljs-params">value</span>  =&gt;</span>  <span class="hljs-keyword">typeof</span>  value === <span class="hljs-string">'string'</span>);
checkString;

<span class="hljs-comment">// Refer to previous code snippet</span>
</code></pre>
<p><code>checkString</code> is a variable whose value is a function. We pass two arguments into this function. </p>
<p><code>'Twitter'</code> is the first argument and the second is an asynchronous function. This function has no one name and has only one task: to check whether the given value is a string.</p>
<p><img src="https://memegenerator.net/img/instances/81322055.jpg" alt="Principles Meme" width="600" height="400" loading="lazy"></p>
<h2 id="heading-principles-of-functional-programming">Principles of Functional Programming</h2>
<p>Earlier in the article I alluded to the fact that merely using functions does not translate to functional programming.</p>
<p>There are some principles we need to understand if our programs are to qualify for the functional programming standard. Let's look at those.</p>
<h3 id="heading-avoid-mutations-and-side-effects">Avoid Mutations and Side effects.</h3>
<p>The first principle of functional programming is to avoid changing things. A function should not change anything such as a global variable.</p>
<p>This is very important because changes often lead to bugs. If a function changes a global variable, for example, it might lead to unexpected behavior in all the places where that variable is used.</p>
<p>The second principle is that a function must be pure, meaning it has no side effects. In functional programming, changes that are made are called mutations, and the outcomes are called side effects.</p>
<p>A pure function does neither of the two. A pure function will always have the same output for the same input.</p>
<p>If a function depends on a global variable, that variable should be passed to the function as an argument. This allows us to obtain the same output for the same input.</p>
<p>Here is an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> legalAgeInTheUS = <span class="hljs-number">21</span>;
<span class="hljs-keyword">const</span> checkLegalStatus = <span class="hljs-function">(<span class="hljs-params">age, legalAge</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> age &gt;= legalAge ? <span class="hljs-string">'Of legal age.'</span> : <span class="hljs-string">'Not of legal age.'</span>;
};
<span class="hljs-keyword">const</span> johnStatus = checkLegalStatus(<span class="hljs-number">18</span>, legalAgeInTheUS);
johnStatus; <span class="hljs-comment">// Not of legal age</span>
legalAgeInTheUS; <span class="hljs-comment">// 21</span>
</code></pre>
<h3 id="heading-abstraction">Abstraction</h3>
<p>Abstractions hide details and allow us to talk about problems at a higher level without describing all the implementation details of the problem.</p>
<p>We use abstractions in all almost all aspects of our lives, especially in speech.</p>
<p>For example, instead of saying <em>"I'm going to exchange money for a machine that once plugged in displays moving images accompanied with sound"</em>, you are most likely to say <em>"I'm going to buy a television"</em>.</p>
<p>In this case <strong>buy</strong> and <strong>television</strong> are abstractions. These forms of abstractions make speech a lot more easier and reduce the chances of saying the wrong thing.</p>
<p>But you'll agree with me that before using abstract terms like <strong>buy</strong> you need to first understand the meaning of the term and the problem it abstracts.</p>
<p>Functions allow us to achieve something similar. We can create functions for tasks that we are most likely to repeat again and again. Functions allows us to create our own abstractions.</p>
<p>On top of creating our own abstractions, some functions have already been created for us to abstract tasks that we are most likely to do time and again.</p>
<p>So we are going to look at some of these higher order functions that already exist to abstract repetitive tasks.</p>
<h3 id="heading-filtering-arrays">Filtering Arrays</h3>
<p>When working with data structures like arrays, we are most likely to find ourselves in a situation where we are only interested in certain items in the array.</p>
<p>To obtain these items we can easily create a function to do the task:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">filterArray</span>(<span class="hljs-params">array, test</span>) </span>{
    <span class="hljs-keyword">const</span> filteredArray = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> item <span class="hljs-keyword">of</span> array) {
        <span class="hljs-keyword">if</span> (test(item)) {
            filteredArray.push(item);
        }
    }
    <span class="hljs-keyword">return</span> filteredArray;
};
<span class="hljs-keyword">const</span> mixedArray = [<span class="hljs-number">1</span>, <span class="hljs-literal">true</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">"Hello"</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">"World"</span>, <span class="hljs-literal">false</span>];
<span class="hljs-keyword">const</span> onlyStrings = filterArray(mixedArray, <span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> <span class="hljs-keyword">typeof</span> item === <span class="hljs-string">'string'</span>);
onlyStrings; <span class="hljs-comment">// ['Hello', 'World']</span>
</code></pre>
<p><code>filterArray</code> is a function that accepts an array and a callback function. It loops through the array and adds the items that pass the test in the callback function into an array called <code>filteredArray</code>.</p>
<p>Using this function we are able to filter an array and return items that we're interested in, such as in the case of <code>mixedArray</code>.</p>
<p>Imagine if we had 10 different programs and in each program we needed to filter an array. Sooner or later it would become extremely tiresome to rewrite the same function over and over again.</p>
<p>Luckily someone already thought about this. Arrays have a standard <code>filter</code> method. It returns a new array with the items in the array it receives that pass the test that we provide.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> mixedArray = [<span class="hljs-number">1</span>, <span class="hljs-literal">true</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">"Hello"</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">"World"</span>, <span class="hljs-literal">false</span>];
<span class="hljs-keyword">const</span> stringArray = mixedArray.filter(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> <span class="hljs-keyword">typeof</span> item === <span class="hljs-string">'string'</span>)
stringArray; <span class="hljs-comment">// ['Hello', 'World']</span>
</code></pre>
<p>Using the standard filter method we were able to achieve the same results we did when we defined our own function in the previous example. So, the filter method is an abstraction of the first function we wrote.</p>
<h3 id="heading-transforming-array-items-with-map">Transforming Array Items With Map</h3>
<p>Imagine another scenario where we have an array of items but we would like to perform a certain operation on all the items. We can write a function to do this for us:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transformArray</span>(<span class="hljs-params">array, test</span>) </span>{
    <span class="hljs-keyword">const</span> transformedArray = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> item <span class="hljs-keyword">of</span> array) {
        transformedArray.push(test(item));
    }
    <span class="hljs-keyword">return</span> transformedArray;
};
<span class="hljs-keyword">const</span> ages = [<span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">21</span>, <span class="hljs-number">19</span>, <span class="hljs-number">32</span>];
<span class="hljs-keyword">const</span> doubleAges = transformArray(ages, <span class="hljs-function"><span class="hljs-params">age</span> =&gt;</span> age * <span class="hljs-number">2</span>);
doubleAges; <span class="hljs-comment">// [24, 30, 42, 38, 64];</span>
</code></pre>
<p>Just like that we  have created a function that loops through any given array and transforms all the items in the array based on the callback function the we provide.</p>
<p>But again this would grow tedious if we had to rewrite the function in 20 different programs.</p>
<p>Again, someone thought about this for us, and luckily arrays have a standard method called <code>map</code> which does the same exact thing. It applies the callback function on all the items in the given array and then it returns a new array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> ages = [<span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">21</span>, <span class="hljs-number">19</span>, <span class="hljs-number">32</span>];
<span class="hljs-keyword">const</span> doubleAges = ages.map(<span class="hljs-function"><span class="hljs-params">age</span> =&gt;</span> age * <span class="hljs-number">2</span>);
doubleAges; <span class="hljs-comment">// [24, 30, 42, 38, 64];</span>
</code></pre>
<h3 id="heading-reducing-arrays-with-reduce">Reducing Arrays with Reduce</h3>
<p>Here's another scenario: You have an array of numbers, but you would like to compute the sum of all these numbers and return it. Of course you can write a function to do this for you.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reduceArray</span>(<span class="hljs-params">array, test, start</span>) </span>{
    <span class="hljs-keyword">let</span> sum = start;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> item <span class="hljs-keyword">of</span> array) {
        sum = test(sum, item)
    }
    <span class="hljs-keyword">return</span> sum;
}
<span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-number">20</span>];
<span class="hljs-keyword">let</span> doubleNumbers = reduceArray(numbers, <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b, <span class="hljs-number">0</span>);
doubleNumbers; <span class="hljs-comment">// 35</span>
</code></pre>
<p>Similar to the previous examples we just looked at, arrays have a standard <code>reduce</code> method that has the same logic as the function we just wrote above.</p>
<p>The reduce method is used to reduce an array to a single value based on the callback function that we provide. It also takes an optional second argument which specifies where we want the operation in the callback to start from.</p>
<p>The callback function we provide in the reduce function has two parameters. The first parameter is the first item in the array by default. Otherwise it is the second argument we provide into the reduce method. The second parameter is the current item in the array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-number">20</span>];
<span class="hljs-keyword">let</span> doubleNumbers = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b, <span class="hljs-number">10</span>);
doubleNumbers;  <span class="hljs-comment">// 45</span>

<span class="hljs-comment">//The above example uses the reduce method to add all the items in the array starting from 10.</span>
</code></pre>
<h2 id="heading-other-useful-array-methods">Other Useful Array Methods</h2>
<h3 id="heading-arraysome">Array.some()</h3>
<p>All arrays have the <code>some</code> method which accepts a callback function. It returns <code>true</code> if <strong>any</strong> element in the array passes the test given in the callback  function. Otherwise it returns <code>false</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">12</span>, <span class="hljs-number">34</span>, <span class="hljs-number">75</span>, <span class="hljs-number">23</span>, <span class="hljs-number">16</span>, <span class="hljs-number">63</span>]
<span class="hljs-built_in">console</span>.log(numbers.some(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> item &lt; <span class="hljs-number">100</span>)) <span class="hljs-comment">// true</span>
</code></pre>
<h3 id="heading-arrayevery">Array.every()</h3>
<p>The every method is the opposite of the some method. It also accepts a callback function and returns <code>true</code> if <strong>all</strong> the items in the array pass the test given in the callback  function. Otherwise it returns <code>false</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">12</span>, <span class="hljs-number">34</span>, <span class="hljs-number">75</span>, <span class="hljs-number">23</span>, <span class="hljs-number">16</span>, <span class="hljs-number">63</span>]
<span class="hljs-built_in">console</span>.log(numbers.every(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> item &lt; <span class="hljs-number">100</span>)) <span class="hljs-comment">// true</span>
</code></pre>
<h3 id="heading-arrayconcat">Array.concat()</h3>
<p>The <code>concat</code> method, short for concatenate, is a standard array method that concatenates or joins two arrays and returns a new array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> array1 = [<span class="hljs-string">'one'</span>, <span class="hljs-string">'two'</span>, <span class="hljs-string">'three'</span>];
<span class="hljs-keyword">const</span> array2 = [<span class="hljs-string">'four'</span>, <span class="hljs-string">'five'</span>, <span class="hljs-string">'six'</span>];
<span class="hljs-keyword">const</span> array3 = array1.concat(array2);
array3; <span class="hljs-comment">// [ 'one', 'two', 'three', 'four', 'five', 'six' ]</span>
</code></pre>
<h3 id="heading-arrayslice">Array.slice()</h3>
<p>The <code>slice</code> method is an array method which copies the items of an array from a given index and returns a new array with the copied items. The <code>slice</code> method accepts two arguments.</p>
<p>The first argument receives the index from which to begin copying. The second argument receives the index from which to stop copying. It returns a new array with the copied items from the starting index (exclusive) to the final index (inclusive).</p>
<p>Note however that the slice method does not use zero indexing. So the index of the first array item is 1 not 0:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>];
<span class="hljs-built_in">console</span>.log(theArray.slice(<span class="hljs-number">1</span>, <span class="hljs-number">4</span>)); <span class="hljs-comment">// [ 2, 3, 4 ]</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you enjoyed reading this article and learned something new at the same time. </p>
<p>There are lots of array and string methods that I didn't mention in the article. If you wish, take some time to do some research on those methods.</p>
<p><em>If you would like to connect with me or to just say hi? feel free to do so via  <a target="_blank" href="http://twitter.com/joeepm">Twitter</a> . I also share interesting tips and resources  for developers.</em> ?</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Principles of Functional Programming ]]>
                </title>
                <description>
                    <![CDATA[ By Yann Salmon In this post, I will lay down the major principles of Functional Programming, starting with the basics and then exploring more advanced concepts. I'll first talk about why you should bother with Functional Programming, that is when it'... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-principles-of-functional-programming/</link>
                <guid isPermaLink="false">66d461723a8352b6c5a2ab29</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 02 Sep 2020 09:27:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/08/fp-cover-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Yann Salmon</p>
<p>In this post, I will lay down the major principles of Functional Programming, starting with the basics and then exploring more advanced concepts.</p>
<p>I'll first talk about why you should bother with Functional Programming, that is when it's useful and when it's not.</p>
<p>We will cover a lot of stuff here, so please go at your own pace. Take some breaks and naps between your reading sessions and do the exercises I propose.</p>
<p>Of course, you can skip sections or go back and fourth depending on your needs.</p>
<p>This post intentionally targets several kind of readers:</p>
<ol>
<li>Those who know almost nothing about FP but are pretty familiar with JavaScript</li>
<li>Those with an Intermediate knowledge of FP and some familiarity with the paradigm, but who want a clearer picture of the whole and want to explore advanced concepts</li>
<li>Those who know a lot about FP and want a cheatsheet+ to revisit some concepts if needed</li>
</ol>
<p>I invite you to ponder each sentence carefully instead of rushing through the content like we're all used to.</p>
<p>I hope this post will be an important milestone in your journey into Functional Programming, as well as a source of information to go back to when needed.</p>
<p>Just a heads up, though – this post doesn't constitute a single source of truth but rather an invitation to go further after reading it.</p>
<p>In other words, it's meant to be revisited and expanded with further resources and practice.</p>
<p>I hope to clarify the functional landscape in your mind, spark your interest for what you didn't know, and more importantly, provide useful tools for your day-to-day projects.</p>
<p>Without further ado, let's get started!</p>
<h2 id="heading-why-functional-programming">Why Functional Programming?</h2>
<p>In my opinion, there are 3 major benefits to FP and 3 (little) drawbacks:</p>
<p>Advantages:</p>
<ol>
<li>More readability, thus maintainability</li>
<li>Less buggy, especially in concurrent contexts</li>
<li>A new way of thinking about problem solving</li>
<li>(Personal bonus) Just great to learn about!</li>
</ol>
<p>Drawbacks:</p>
<ol>
<li>Can have performance issues</li>
<li>Less intuitive to work with when dealing with state and I/O</li>
<li>Unfamiliar for most people + math terminology that slows the learning process</li>
</ol>
<p>Now I'll explain why I think that.</p>
<h3 id="heading-increased-readability">Increased Readability</h3>
<p>First, Functional Programming is often more readable because of its <strong>declarative</strong> nature.</p>
<p>In other words, the code is focused on describing the outcome of the computations, not the computations themselves.</p>
<p><a target="_blank" href="https://github.com/getify/Functional-Light-JS/blob/master/manuscript/ch1.md/#chapter-1-why-functional-programming">Kyle Simpson</a> phrases it like this:</p>
<blockquote>
<p>Declarative code is code that's more focused on describing the "what" outcome. Imperative code (the opposite) is focused on precisely instructing the computer "how" to do something.</p>
</blockquote>
<p>Because we spend the vast majority of our time reading code (around 80% of the time I guess) and not writing it, readability is the first thing we should enhance in order to increase our efficiency when programming.</p>
<p>It's also very likely that you'll return back to a project after several weeks of not touching it, so all the context loaded in your short-term memory will have disappeared.</p>
<p>Thus, understanding your <strong>imperative</strong> code will not be as easy as it was.</p>
<p>The same thing goes for the potential colleagues that work with you on the project.</p>
<p>So readability is a huge advantage for an ever more important purpose: maintainability.</p>
<p>I could stop arguing right there. Increased readability should give you major motivation to learn Functional Programming.</p>
<p>Luckily, that's an advantage that you'll experience more and more as you get familiar with the paradigm.</p>
<p>No need to be an expert. The moment you write a declarative line of code you'll experience it.</p>
<p>Now the second argument.</p>
<h3 id="heading-less-buggy-code">Less buggy code</h3>
<p>Functional programs are less buggy, especially in concurrent contexts.</p>
<p>Because the functional style strives to avoid mutations, shared resources will not have unexpected contents.</p>
<p>For example, imagine that 2 threads access the same variable.</p>
<p>If this variable can be mutated, then, as the programs grow, you'll likely not get what you want when re-accessing it.</p>
<p>In addition, the rise of multiprocessor systems allows multiple threads to execute in parallel.</p>
<p>So now there's also a risk of overlapping (one thread may try to write while the other tries to read).</p>
<p>It's kind of a shame not to leverage the hardware because we're not able to make the software work.</p>
<p>However, JavaScript is single-threaded and my personal experience doesn't expand much beyond it.</p>
<p>Thus, I'm less confident in this argument, but more experienced programmers seem to agree on that fact (for what I've heard/read).</p>
<h3 id="heading-problem-solving">Problem solving</h3>
<p>Finally, the last advantage – and more important than you might think – is that Functional Programming gives you a new way of thinking about problem solving.</p>
<p>You might be so used to solving problems using classes and objects (Object-Oriented Programming) that you don't even think there might be a better way to do so.</p>
<p>I'm not saying that Functional Programming is always better.</p>
<p>I'm saying that it will be better in certain cases and that having this knowledge will (re)open your mind and make you a better programmer.</p>
<p>Because now you'll have more tools and an increased capacity to choose the right one for the problem at hand.</p>
<p>I even think that some core principles in FP can translate to problem solving outside the domain of computers.</p>
<p>Let's see the drawbacks now.</p>
<h3 id="heading-performance-issues">Performance issues</h3>
<p>The first is that, by applying FP techniques, you can end up using a lot of time and/or memory.</p>
<p>Because you don't want to mutate things, the process is basically to copy the data, then mutate that copy and use it as the current state.</p>
<p>This means that the original data is left untouched but you allocate a bunch of time and memory to make the new copy.</p>
<p>So when you make a lot of copies (really big nested objects) or use techniques like recursion (accumulating layers in the callstack), performance issues may appear.</p>
<p>However, many solutions exist (structural sharing, tail-call optimization) which make poor performance very rare.</p>
<h3 id="heading-less-intuitive">Less intuitive</h3>
<p>The second drawback is when you need state or I/O operations.</p>
<p>Well, you're gonna say:</p>
<blockquote>
<p>Computers are stateful machines! And eventually I'll need to call my database, or display something on the screen, or write a file.</p>
</blockquote>
<p>I totally agree.</p>
<p>The thing is to remember that Functional Programming is a style convenient for humans, but machines make imperative operations (aka mutations) all the time.</p>
<p>That's just how it works at the lowest level.</p>
<p>The computer is in one state at a given moment and it changes all the time.</p>
<p>The point of FP is to ease our reasoning about the code which increases the chances that the messy stuff that comes out of it actually works.</p>
<p>And Functional Reactive Programming helps us deal with state (if you want to learn more, there are links at the end of the post).</p>
<p>Even if imperative code seems easier/more intuitive at first sight, you'll eventually lose track. I'm pretty confident that if you make the initial efforts of learning FP, it will pay off.</p>
<p>For I/O – short for Input/Output, that is code that transfers data to or from a computer and to or from a peripheral device – we can't have pure isolated functions anymore.</p>
<p>To deal with that, we can take a <a target="_blank" href="https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell">Functional Core Imperative Shell</a> approach.</p>
<p>In other words, we want to do as much as we can in a functional way and push back the I/O operations to the outer layer of the program:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/fp-core-imperative-shell-1.png" alt="Functional Core Imperative Shell" width="600" height="400" loading="lazy"></p>
<h3 id="heading-steeper-learning-curve">Steeper learning curve</h3>
<p>Finally, the last drawback is that Functional Programming is kind of cluttered with math terminology. This often creates unnecessary friction when developers are trying to learn it.</p>
<p>It's likely because this style of programming first appeared in the academic world and stayed there a long time before emerging and becoming more popular.</p>
<p>However, these technical/unfamiliar terms shouldn't make you neglect the very powerful mathematical principles that underlie them.</p>
<p>All in all, I think the strengths of FP outweigh the weaknesses.</p>
<p>And functional programming makes a lot of sense for the majority of general-purpose JavaScript programming.</p>
<p>Just keep in mind that there are few programs with peculiar requirements for which FP is not a good fit. But if that's not your case, there's no reason not to leverage this paradigm.</p>
<p>Now, if you're a total beginner you might be feeling a bit lost. It's ok – bear with me. The following sections will clarify the concepts I referred to here.</p>
<p>Now let's dive into the nuts and bolts of functional programming.</p>
<h2 id="heading-data-calculations-and-actions">Data, Calculations, and Actions</h2>
<p>In FP, you can break down your program in 3 parts: data, calculations and actions.</p>
<h3 id="heading-data">Data</h3>
<p>The data is, well, the data. In our languages, they have different forms, different types.</p>
<p>In JavaScript you have numbers, strings, arrays, objects, and so on. But at the end of the day, they are just bits.</p>
<p>Data are the building blocks of the program. Having none of it is like having no water in an aquatic park.</p>
<p>Then we can do things with the data: calculations or actions. </p>
<h3 id="heading-calculations">Calculations</h3>
<p>Calculations are mathematical-like transformations of the data. </p>
<p>Functions are a way to create them. You provide it a set of inputs and it returns you a set of outputs.</p>
<p>That's it.</p>
<p>It does nothing outside the function, like in math. The world around the function is not impacted.</p>
<p>In addition, if you feed the function with the same input multiple times, it should always give you the same output.</p>
<p>A common term for this type of function is <strong>pure function</strong>. </p>
<p>Because of its characteristics, its entire behavior is known in advance. In fact, because it just returns a value, we can treat it as that value, as data.</p>
<p>In other words, we could replace the function call by the value it returns and it would not change the state of the program.</p>
<p>This is called <strong>referential transparency</strong>. Thus, they're really easy to reason about, and you can use them as function input or output and assign them to variables.</p>
<p>These kinds of functions are called <strong>first-class</strong> functions. In JavaScript, all functions are first-class.</p>
<p>It's safe to use pure functions because, again, they're like values.</p>
<p>For functions that do more than return a value, you rely on human memory. That's a bad strategy, especially for large software with multiple people working on it.</p>
<p>So you can use <strong>pure functions</strong> as a replacement for <strong>calculations</strong>. They are identical.</p>
<p>Now let's talk about actions.</p>
<h3 id="heading-actions">Actions</h3>
<p>Of course, we also need functions that impact the outside world, that actually do something. Otherwise, your program would be a calculator without screen.</p>
<p>When a function impacts things outside of itself, we say that it has <strong>side-effects</strong>. As opposed to pure functions, it is said to be <strong>impure</strong>.</p>
<p>Common side-effects are assignments/mutations of variables outside the function, logging to the console, making an API call, and so on.</p>
<p>So basically, <strong>actions</strong> and <strong>impure functions</strong> are the same.</p>
<p>Here's a simple example to illustrate these concepts:</p>
<pre><code class="lang-js">
<span class="hljs-comment">// ↓ variable</span>
<span class="hljs-comment">//      ↓ data</span>
<span class="hljs-keyword">let</span> a = <span class="hljs-number">3</span>;

<span class="hljs-comment">// Calculation / Pure function</span>
<span class="hljs-keyword">const</span> double = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x * <span class="hljs-number">2</span>;

double(a);
<span class="hljs-comment">// 6</span>

<span class="hljs-comment">// Action / Impure function</span>
<span class="hljs-keyword">const</span> IncThenPrint = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// assignment of a variable outside the scope of the function</span>
  a = a + <span class="hljs-number">1</span>;

  <span class="hljs-comment">// do something (here printing) outside the function</span>
  <span class="hljs-built_in">console</span>.log(a);
};

IncThenPrint();
<span class="hljs-comment">// console: 4</span>
</code></pre>
<h3 id="heading-data-calculations-and-actions-in-functional-programming">Data, calculations, and actions in functional programming</h3>
<p>In FP, the objective is to separate the data, the calculations, and the actions while striving to do most of the job with calculations.</p>
<p>Why? Because actions rely on the outside world. We don't have total control on it.</p>
<p>Thus, we may get unexpected results/behaviors out of it. So if the majority of your program is made of actions, it quickly becomes a mess.</p>
<p>Taking the previous example, what if somewhere else in the program, someone decided to assign an object to the variable <code>a</code> ?</p>
<p>Well, we'll get an unexpected result when running <code>IncThenPrint</code> because it makes no sense to add 1 to an object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = <span class="hljs-number">3</span>;

<span class="hljs-comment">// ...</span>
a = { <span class="hljs-attr">key</span>: <span class="hljs-string">"value"</span> };
<span class="hljs-comment">// ...</span>

<span class="hljs-comment">// Action / Impure function</span>
<span class="hljs-keyword">const</span> IncThenPrint = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// assignment of a variable outside the scope of the function</span>
  a = a + <span class="hljs-number">1</span>;

  <span class="hljs-comment">// do something (here printing) outside the function</span>
  <span class="hljs-built_in">console</span>.log(a);
  <span class="hljs-comment">// prints: 4</span>
};

IncThenPrint();
<span class="hljs-comment">// prints: [object Object]1</span>
<span class="hljs-comment">// (Because JavaScript is a dynamically-typed language, it converts both operands of the + operator</span>
<span class="hljs-comment">// to strings so it can perform the operation, thus explaining the result.</span>
<span class="hljs-comment">// But obviously, that not what was intended.)</span>
</code></pre>
<p>The ability to differentiate data, calculations, and actions in your program is a fundamental skill to develop.</p>
<h3 id="heading-mapping">Mapping</h3>
<p>Mapping is a fairly trivial but very important concept in the world of functional programming.</p>
<p>"Mapping from A to B" means going from A to B via some association.</p>
<p>In other words, A points to B by means of some linkage between them.</p>
<p>For example, a pure function maps an input to an output. We can write it like this: input --&gt; output; where the arrow indicates a function.</p>
<p>Another example are objects in JavaScript. They map keys to values.</p>
<p>In other languages, this data structure is often called a "map" or "hash-map", which is more explanatory.</p>
<p>Like the latter term infers, the thing that happens behind the scene is that each key is linked to its value via a <em>hash</em> function. The key is passed to the <em>hash</em> function which returns the index of the corresponding value in the array that stores them all.</p>
<p>Without going into further detail, I wanted to introduce this term because I'll use it throughout this article.</p>
<h3 id="heading-more-on-side-effects">More on side-effects</h3>
<p>Before we move on, I want to go deeper into side-effects in JavaScript and showcase a vicious pitfall that you may not be aware of.</p>
<p>To remind ourselves, saying that a function has side-effects is the same as saying, "When this function runs, something outside of its scope will change."</p>
<p>Like I said, it can be logging to the console, making an API call, changing an outer variable, etc.</p>
<p>Let's see an example of the latter:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> y;

<span class="hljs-keyword">const</span> f = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> {
  y = x * x;
};

f(<span class="hljs-number">5</span>);
y; <span class="hljs-comment">// 25</span>
</code></pre>
<p>That's pretty easy to grasp.</p>
<p>When <code>f</code> runs, it assigns a new value to the outer variable <code>y</code>, which is a side-effect.</p>
<p>A pure version of this example would be:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> f = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x * x;

<span class="hljs-keyword">const</span> y = f(<span class="hljs-number">5</span>);
<span class="hljs-comment">// 25</span>
</code></pre>
<p>But there's another way to change an outer variable that's more subtle:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, { <span class="hljs-attr">key</span>: <span class="hljs-string">"value"</span> }, <span class="hljs-string">"a string"</span>, <span class="hljs-number">4</span>];

<span class="hljs-keyword">const</span> g = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> total = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Number</span>.isNaN(<span class="hljs-built_in">Number</span>(arr[i]))) {
      arr[i] = <span class="hljs-number">0</span>;
    }
    total += arr[i];
  }

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

g(myArr);
<span class="hljs-comment">// 10</span>
myArr;
<span class="hljs-comment">// [1, 2, 3, 0, 0, 4]</span>
<span class="hljs-comment">// Oops, all elements that were not numbers have been changed to 0 !</span>
</code></pre>
<p>Why is that?</p>
<p>In JavaScript, when assigning a value to a variable or passing it to a function, it's automatically copied.</p>
<p>But there's a distinction to make here.</p>
<p><strong>Primitive values</strong> (<code>null</code>, <code>undefined</code>, strings, numbers, booleans and symbols) are always assigned/passed by <strong>value-copy</strong>.</p>
<p>In contrast, <strong>compound values</strong> like objects, arrays and functions (by the way, arrays and functions are objects in JavaScript, but I don't refer to them as objects for clarity) create a copy by <strong>reference</strong> on assignment or passing.</p>
<p>So in the previous example, the value passed to <code>g</code> is a compound one, the array <code>myArr</code>.</p>
<p>What happens is that <code>g</code> stores the memory address of <code>myArr</code> in <code>arr</code>, the parameter's name used in the function's body.</p>
<p>In other words, there's no value-copy of each elements in <code>myArr</code> like you would expect. Thus, when you manipulate or change <code>arr</code>, it actually goes to <code>myArr</code> memory's location and perform whatever computation you specified.</p>
<p>So yeah, be aware of that quirk.</p>
<h3 id="heading-exercises-set-1">Exercises (Set 1)</h3>
<ol>
<li>In the snippet below, find the pure functions and the impure ones:</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// a</span>
<span class="hljs-keyword">const</span> capitalizeFirst = <span class="hljs-function">(<span class="hljs-params">str</span>) =&gt;</span> str.charAt(<span class="hljs-number">0</span>).toUpperCase() + str.slice(<span class="hljs-number">1</span>);

<span class="hljs-comment">// b</span>
<span class="hljs-keyword">const</span> greeting = <span class="hljs-function">(<span class="hljs-params">persons</span>) =&gt;</span> {
  persons.forEach(<span class="hljs-function">(<span class="hljs-params">person</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> fullname = <span class="hljs-string">`<span class="hljs-subst">${capitalizeFirst(person.firstname)}</span> <span class="hljs-subst">${capitalizeFirst(
      person.lastname
    )}</span>`</span>;

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello <span class="hljs-subst">${fullname}</span> !`</span>);
  });
};

<span class="hljs-comment">// c</span>
<span class="hljs-keyword">const</span> getLabels = <span class="hljs-keyword">async</span> (endpoint) =&gt; {
  <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://my-database-api/"</span> + endpoint);
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json();
  <span class="hljs-keyword">return</span> data.labels;
};

<span class="hljs-comment">// d</span>
<span class="hljs-keyword">const</span> counter = <span class="hljs-function">(<span class="hljs-params">start, end</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> start === end
    ? <span class="hljs-string">"End"</span>
    : <span class="hljs-comment">// e</span>
      <span class="hljs-function">() =&gt;</span> counter(start + <span class="hljs-number">1</span>, end);
};
</code></pre>
<ol start="2">
<li>Convert this snippet into a pure one (you can make more than one function if you feel the need to):</li>
</ol>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> people = [
  { <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Bill"</span>, <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Harold"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">54</span> },
  { <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Ana"</span>, <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Atkins"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">42</span> },
  { <span class="hljs-attr">firstname</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Doe"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">57</span> },
  { <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Davy"</span>, <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Johnson"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">34</span> },
];

<span class="hljs-keyword">const</span> parsePeople = <span class="hljs-function">(<span class="hljs-params">people</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> parsedPeople = [];

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; people.length; i++) {
    people[i].firstname = people[i].firstname.toUpperCase();
    people[i].lastname = people[i].lastname.toUpperCase();
  }

  <span class="hljs-keyword">const</span> compareAges = <span class="hljs-function">(<span class="hljs-params">person1, person2</span>) =&gt;</span> person1.age - person2.age;

  <span class="hljs-keyword">return</span> people.sort(compareAges);
};

parsePeople(people);
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   {firstname: "DAVY", lastname: "JOHNSON", age: 34},</span>
<span class="hljs-comment">//   {firstname: "ANA", lastname: "ATKINS", age: 42},</span>
<span class="hljs-comment">//   {firstname: "BILL", lastname: "HAROLD", age: 54},</span>
<span class="hljs-comment">//   {firstname: "JOHN", lastname: "DOE", age: 57},</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<p><a target="_blank" href="https://www.freecodecamp.org/news/the-principles-of-functional-programming/#set-1">Check answers</a>.</p>
<h2 id="heading-immutability">Immutability</h2>
<p>Like we've seen previously, a common side-effect is to mutate a variable.</p>
<p>You don't want to do that in functional programming. So an important characteristic of a functional program is the <strong>immutability</strong> of data.</p>
<p>In functional languages like Clojure and Haskell, this feature is built-in – you have no way to mutate the data unless the language allows it. In any case, you must consciously opt to do so.</p>
<p>But in JavaScript, that's not the case.</p>
<p>So it's more about having the "immutability" mindset than a real robust implementation of this feature.</p>
<p>What this means is that you will basically make copies of the data you want to work on.</p>
<p>In the first section, we saw that JavaScript functions automatically make copies of the arguments passed. While primitive values are copied by value, compound values are only copied by reference, so it's still possible to mutate them.</p>
<p>Thus, when working with an object/array in a function, you should make a copy and then operate on it.</p>
<p>By the way, notice that some built-in functions doesn't mutate the value it's called upon, while others do.</p>
<p>For example, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">Array.prototype.map</a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">Array.prototype.filter</a>, or <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">Array.prototype.reduce</a> are don't mutate the original array.</p>
<p>On the other hand, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse">Array.prototype.reverse</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push">Array.prototype.push</a> are mutate the original array.</p>
<p>You can find out if a built-in function mutates the value it's called upon or not in the documentation, so check it out if you're not sure.</p>
<p>That's annoying, and ultimately not perfectly safe.</p>
<h3 id="heading-shallow-vs-deep-copies">Shallow vs. deep copies</h3>
<p>Since ES6, it's easy to make object/array copies through spread notation, <a target="_blank" href="https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/from"><code>Array.from()</code></a>, <a target="_blank" href="https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/assign"><code>Object.assign()</code></a>.</p>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// arrays</span>
<span class="hljs-keyword">const</span> fruits = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"strawberry"</span>, <span class="hljs-string">"banana"</span>];
<span class="hljs-keyword">const</span> fruitsCopy = [...fruits];
fruitsCopy[<span class="hljs-number">0</span>] = <span class="hljs-string">"mutation"</span>;
<span class="hljs-comment">// fruitsCopy: ['mutation', 'strawberry', 'banana']</span>
<span class="hljs-comment">// fruits (not mutated): ['apple', 'strawberry', 'banana']</span>

<span class="hljs-comment">// objects</span>
<span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">c</span>: <span class="hljs-number">3</span> };
<span class="hljs-keyword">const</span> objCopy = { ...obj };
objCopy.a = <span class="hljs-string">"mutation"</span>;
<span class="hljs-comment">// objCopy: {a: "mutation", b: 2, c: 3}</span>
<span class="hljs-comment">// obj (not mutated): {a: 1, b: 2, c: 3}</span>
<span class="hljs-built_in">console</span>.log(obj);
<span class="hljs-built_in">console</span>.log(objCopy);
</code></pre>
<p>That's cool but there's a gotcha.</p>
<p>Spread arrays/objects only have there first level copied by value, also known as a <strong>shallow</strong> copy.</p>
<p>So all subsequent levels are still mutable:</p>
<pre><code class="lang-js"><span class="hljs-comment">// But with nested objects/arrays, that doesn't work</span>
<span class="hljs-keyword">const</span> nestedObj = { <span class="hljs-attr">a</span>: { <span class="hljs-attr">b</span>: <span class="hljs-string">"canBeMutated"</span> } };
<span class="hljs-keyword">const</span> nestedObjCopy = { ...nestedObj };
nestedObjCopy.a.b = <span class="hljs-string">"hasBeenMutated!"</span>;
<span class="hljs-built_in">console</span>.log(nestedObj);
<span class="hljs-built_in">console</span>.log(nestedObjCopy);
<span class="hljs-comment">// nestedObjCopy: {a: {b: "hasBeenMutated!"}}}</span>
<span class="hljs-comment">// nestedObj (mutated): {a: {b: "hasBeenMutated!"}}</span>
</code></pre>
<p>To resolve this problem, we need a custom function to do <strong>deep</strong> copies. This <a target="_blank" href="https://medium.com/javascript-in-plain-english/how-to-deep-copy-objects-and-arrays-in-javascript-7c911359b089">article</a> discusses multiple solutions.</p>
<p>Here's a shortened version of the custom function proposed in it:</p>
<pre><code class="lang-js"><span class="hljs-comment">// works for arrays and objects</span>
<span class="hljs-keyword">const</span> deepCopy = <span class="hljs-function">(<span class="hljs-params">obj</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> obj !== <span class="hljs-string">"object"</span> || obj === <span class="hljs-literal">null</span>) {
    <span class="hljs-keyword">return</span> obj; <span class="hljs-comment">// Return the value if obj is not an object</span>
  }

  <span class="hljs-comment">// Create an array or object to hold the values</span>
  <span class="hljs-keyword">let</span> newObj = <span class="hljs-built_in">Array</span>.isArray(obj) ? [] : {};

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> key <span class="hljs-keyword">in</span> obj) {
    <span class="hljs-comment">// Recursively (deep) copy for nested objects, including arrays</span>
    newObj[key] = deepCopy(obj[key]);
  }

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

<span class="hljs-keyword">const</span> nestedObj = {
  <span class="hljs-attr">lvl1</span>: { <span class="hljs-attr">lvl2</span>: { <span class="hljs-attr">lvl3</span>: { <span class="hljs-attr">lvl4</span>: <span class="hljs-string">"tryToMutateMe"</span> } } },
  <span class="hljs-attr">b</span>: [<span class="hljs-string">"tryToMutateMe"</span>],
};
<span class="hljs-keyword">const</span> nestedObjCopy = deepCopy(nestedObj);

nestedObjCopy.lvl1.lvl2.lvl3.lvl4 = <span class="hljs-string">"mutated"</span>;
nestedObjCopy.b[<span class="hljs-number">0</span>] = <span class="hljs-string">"mutated"</span>;

<span class="hljs-built_in">console</span>.log(nestedObj);
<span class="hljs-comment">// { lvl1: { lvl2: { lvl3: { lvl4: "tryToMutateMe" } } }, b: ["tryToMutateMe"]}</span>
<span class="hljs-built_in">console</span>.log(nestedObjCopy);
<span class="hljs-comment">// { lvl1: { lvl2: { lvl3: { lvl4: "mutated" } } }, b: ["mutated"]}</span>
</code></pre>
<p>If you already use a library that provides functional utilities, it's likely that it has one to do deep copies. I personally like <a target="_blank" href="https://ramdajs.com">Ramda</a>. See its <a target="_blank" href="https://ramdajs.com/docs/#clone">clone</a> function.</p>
<p>If the difference between shallow and deep copies still isn't clear, check <a target="_blank" href="https://medium.com/@manjuladube/understanding-deep-and-shallow-copy-in-javascript-13438bad941c">this</a> out.</p>
<p>Now let's talk about performance.</p>
<p>Obviously, making copies doesn't come without a cost.</p>
<p>For performance-sensitive parts of the program, or in cases where changes happen frequently, creating a new array or object (especially if it contains lots of data) is undesirable for both processing and memory reasons.</p>
<p>In these cases, using immutable data structures from a library like <a target="_blank" href="https://immutable-js.github.io/immutable-js/">Immutable.js</a> is probably a better idea.</p>
<p>They use a technique called <strong>structural sharing</strong> which I referred to when talking about the downsides of FP earlier in this post.</p>
<p>Check out this great <a target="_blank" href="https://www.youtube.com/watch?v=I7IdS-PbEgI&amp;list=PLts8-qGf74Q5QfIkOPGqwO_7d1ljMWa8p&amp;index=22&amp;t=0s">talk</a> to learn more.</p>
<p>Dealing with immutable data is thus, in my opinion, the second skill to have in your functional programmer tool belt.</p>
<h2 id="heading-composition-and-currying">Composition and Currying</h2>
<h3 id="heading-composition">Composition</h3>
<p>Unsurprisingly, the fundamental building blocks of a functional program are functions.</p>
<p>Because your functions are free of side-effects and considered first-class, we can compose them.</p>
<p>Like I said, <em>first-class</em> means that they're treated as regular data structures, possibly being assigned to variables, passed as arguments, or returned from other functions.</p>
<p>Composition is a powerful idea.</p>
<p>From tiny little functions, you can add up their functionalities to form a more complex one, but without the pain of laying it down upfront.</p>
<p>In addition, you get greater flexibility because you can easily rearrange your compositions.</p>
<p>Being backed up by mathematical laws, we know that everything will work if we follow them.</p>
<p>Let's introduce some code to make things concrete:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> map = <span class="hljs-function">(<span class="hljs-params">fn, arr</span>) =&gt;</span> arr.map(fn);

<span class="hljs-keyword">const</span> first = <span class="hljs-function">(<span class="hljs-params">xs</span>) =&gt;</span> xs[<span class="hljs-number">0</span>];

<span class="hljs-keyword">const</span> formatInitial = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x.toUpperCase() + <span class="hljs-string">"."</span>;

<span class="hljs-keyword">const</span> intercalate = <span class="hljs-function">(<span class="hljs-params">sep, arr</span>) =&gt;</span> arr.join(sep);

<span class="hljs-keyword">const</span> employees = [<span class="hljs-string">"Yann"</span>, <span class="hljs-string">"Brigitte"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"William"</span>];

<span class="hljs-keyword">const</span> initials = intercalate(<span class="hljs-string">"\n"</span>, map(formatInitial, map(first, employees)));
<span class="hljs-comment">// Y.</span>
<span class="hljs-comment">// B.</span>
<span class="hljs-comment">// J.</span>
<span class="hljs-comment">// W.</span>
</code></pre>
<p>Ouch – there's a little bit of nesting here.</p>
<p>Take some time to understand what's going on. As you can see, there are function calls passed as arguments to outer functions.</p>
<p>With the power of <code>map</code>, we essentially composed the functionalities of <code>first</code>, <code>formatInitial</code>, and <code>join</code> to eventually apply them on the <code>employees</code> array.</p>
<p>Pretty cool! </p>
<p>But as you can see, nesting is annoying. It makes things harder to read.</p>
<h3 id="heading-currying">Currying</h3>
<p>To flatten that stuff and make composition a breeze, we have to talk about <strong>currying</strong>.</p>
<p>This term may scare you, but don't worry, it's just jargon for a simple idea: feeding a function one argument at a time.</p>
<p>Usually, when we make a function call, we provide all the arguments at once and get back the result:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> add = <span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> x + y;

add(<span class="hljs-number">3</span>, <span class="hljs-number">7</span>);
<span class="hljs-comment">// 10</span>
</code></pre>
<p>But what if we could pass only one argument and provide the second one later?</p>
<p>Well, we can do that by currying <code>add</code> like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> add = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">y</span>) =&gt;</span> x + y;

<span class="hljs-keyword">const</span> addTo3 = add(<span class="hljs-number">3</span>);
<span class="hljs-comment">// (y) =&gt; 3 + y</span>

<span class="hljs-comment">// ...later</span>
addTo3(<span class="hljs-number">7</span>);
<span class="hljs-comment">// 10</span>
</code></pre>
<p>This can be useful if we don't have all the arguments yet.</p>
<p>You might not understand why we wouldn't have all the arguments beforehand, but you'll see later.</p>
<p>Thanks to closures, we're preloading the function with its arguments step-by-step until we eventually run it.</p>
<p>If you have a hard time grasping the concept of closure, check <a target="_blank" href="https://www.youtube.com/watch?v=CQqwU2Ixu-U">this</a>, then <a target="_blank" href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch7.md#chapter-7-using-closures">this</a> to go deeper.</p>
<p>In short, closure allows an inner function to access variables of an outer function's scope. That's why we can access <code>x</code> in the scope of <code>addTo3</code> which comes from the outer scope, <code>add</code>.</p>
<p>Often you don't want to bother writing your functions in this special form. In addition, you can't always write them this way, for example, when you use external library functions and virtually anything you don't write but use all the same.</p>
<p>For this reason, there's a common helper to curry a function (<a target="_blank" href="https://github.com/getify/Functional-Light-JS/blob/master/manuscript/ch3.md/#currying-more-than-one-argument">from Kyle Simpson book YDKJS</a>):</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> curry = <span class="hljs-function">(<span class="hljs-params">fn, arity = fn.length</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nextCurried</span>(<span class="hljs-params">prevArgs</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">curried</span>(<span class="hljs-params">...nextArgs</span>) </span>{
      <span class="hljs-keyword">const</span> args = [...prevArgs, ...nextArgs];

      <span class="hljs-keyword">return</span> args.length &lt; arity ? nextCurried(args) : fn(...args);
    };
  })([]);
};
</code></pre>
<p><code>curry</code> takes a function and a number called <strong>arity</strong> (optional).</p>
<p>The arity of a function is the number of arguments it takes.</p>
<p>In the case of <code>add</code>, it's 2.</p>
<p>We need that information to know when all the arguments are there, and thus decide to run the function or return another curried function that will take the remaining ones.</p>
<p>So let's refactor our example with <code>add</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> add = curry(<span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> x + y);

<span class="hljs-keyword">const</span> addTo3 = add(<span class="hljs-number">3</span>);

addTo3(<span class="hljs-number">7</span>);
<span class="hljs-comment">// 10</span>
</code></pre>
<p>Or we can still call <code>add</code> with all its arguments directly:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> add = curry(<span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> x + y);

add(<span class="hljs-number">3</span>, <span class="hljs-number">7</span>);
<span class="hljs-comment">// 10</span>
</code></pre>
<h3 id="heading-partial-application">Partial application</h3>
<p>Actually, <em>curried</em> strictly means "takes one argument at a time", no more, no less.</p>
<p>When we can provide the number of arguments we want, we're actually talking about <strong>partial application</strong>.</p>
<p>Thus, currying is a constrained form of partial application.</p>
<p>Let's see a more explicit example of partial application compared to currying:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> listOf4 = curry(<span class="hljs-function">(<span class="hljs-params">a, b, c, d</span>) =&gt;</span> <span class="hljs-string">`1. <span class="hljs-subst">${a}</span>\n2. <span class="hljs-subst">${b}</span>\n3. <span class="hljs-subst">${c}</span>\n4. <span class="hljs-subst">${d}</span>`</span>);

<span class="hljs-comment">// strict currying</span>

<span class="hljs-keyword">const</span> a = listOf4(<span class="hljs-string">"First"</span>)(<span class="hljs-string">"Second"</span>)(<span class="hljs-string">"Third"</span>)(<span class="hljs-string">"Fourth"</span>);
<span class="hljs-comment">// or</span>
<span class="hljs-keyword">const</span> b = listOf4(<span class="hljs-string">"First"</span>);
<span class="hljs-comment">// later</span>
<span class="hljs-keyword">const</span> c = b(<span class="hljs-string">"Second"</span>)(<span class="hljs-string">"Third"</span>);
<span class="hljs-comment">// later</span>
<span class="hljs-keyword">const</span> d = c(<span class="hljs-string">"Fourth"</span>);

<span class="hljs-comment">// partial application</span>

<span class="hljs-keyword">const</span> e = listOf4(<span class="hljs-string">"First"</span>, <span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>, <span class="hljs-string">"Fourth"</span>);
<span class="hljs-comment">// or</span>
<span class="hljs-keyword">const</span> b = listOf4(<span class="hljs-string">"First"</span>);
<span class="hljs-comment">// later</span>
<span class="hljs-keyword">const</span> c = b(<span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>);
<span class="hljs-comment">// later</span>
<span class="hljs-keyword">const</span> d = c(<span class="hljs-string">"Fourth"</span>);
</code></pre>
<p>Do you see the difference?</p>
<p>With currying, you should provide one argument at a time. If you want to feed more than one argument, then you need to make a new function call, hence the pair of parentheses around each argument.</p>
<p>Honestly, that's just a matter of style.</p>
<p>It seems a bit awkward when you're not used to it, but on the other hand, some people find the partial application style to be messy.</p>
<p>The <code>curry</code> helper I introduced allows you to do both. </p>
<p>It stretches the real definition of currying, but I prefer to have both functionalities and don't like the name <code>looseCurry</code> that Kyle Simpson used in is book. So, I cheated a little bit.</p>
<p>Just keep the differences in mind and be aware that <code>curry</code> helpers you find in libraries probably follow the strict definition.</p>
<h3 id="heading-data-comes-last">Data comes last</h3>
<p>A final point I want to make is that we usually place the data as the last argument.</p>
<p>With the previous functions I used, it's not obvious because all arguments are data. But take a look at this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> replace = curry(<span class="hljs-function">(<span class="hljs-params">regex, replacement, str</span>) =&gt;</span>
  str.replace(regex, replacement)
);
</code></pre>
<p>You can see that the data (<code>str</code>) is in the last position because it's likely to be the last thing we'll want to pass through.</p>
<p>You will see that this is the case when composing functions.</p>
<h3 id="heading-bring-it-all-together">Bring it all together</h3>
<p>Now to take advantage of currying and flatten our nested jumble from before, we also need a helper for composition.</p>
<p>You guessed it, it's called <code>compose</code>!:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> compose = <span class="hljs-function">(<span class="hljs-params">...fns</span>) =&gt;</span>
  fns.reverse().reduce(<span class="hljs-function">(<span class="hljs-params">fn1, fn2</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> fn2(fn1(...args)));
</code></pre>
<p><code>compose</code> takes functions as arguments and returns another function which takes the argument(s) to pass through the whole pipeline.</p>
<p>Functions are applied from right to left because of <code>fns.reverse()</code>.</p>
<p>Because <code>compose</code> returns a function that takes the future argument(s), we can freely associate our functions without calling them, which allow us to create intermediate functions.</p>
<p>So with our initial example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> map = <span class="hljs-function">(<span class="hljs-params">fn, arr</span>) =&gt;</span> arr.map(fn);

<span class="hljs-keyword">const</span> first = <span class="hljs-function">(<span class="hljs-params">xs</span>) =&gt;</span> xs[<span class="hljs-number">0</span>];

<span class="hljs-keyword">const</span> formatInitial = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x.toUpperCase() + <span class="hljs-string">"."</span>;

<span class="hljs-keyword">const</span> intercalate = <span class="hljs-function">(<span class="hljs-params">sep, arr</span>) =&gt;</span> arr.join(sep);

<span class="hljs-keyword">const</span> getInitials = compose(formatInitial, first);

<span class="hljs-keyword">const</span> employees = [<span class="hljs-string">"Yann"</span>, <span class="hljs-string">"Brigitte"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"William"</span>];

<span class="hljs-keyword">const</span> initials = intercalate(<span class="hljs-string">"\n"</span>, map(getInitials, employees));
<span class="hljs-comment">// Y.</span>
<span class="hljs-comment">// B.</span>
<span class="hljs-comment">// J.</span>
<span class="hljs-comment">// W.</span>
</code></pre>
<p><code>first</code> and <code>formatInitial</code> already take one argument.</p>
<p>But <code>map</code> and <code>intercalate</code> take 2 arguments, so we can't include them as is in our <code>compose</code> helper because only one argument will be passed. In this case it's an array that both take as a final argument (remember, data is the last thing to get passed).</p>
<p>It would be nice to give <code>map</code> and <code>intercalate</code> their respective first argument in advance.</p>
<p>Wait a minute – we can curry them!:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ...</span>

<span class="hljs-keyword">const</span> map = curry(<span class="hljs-function">(<span class="hljs-params">fn, arr</span>) =&gt;</span> arr.map(fn));

<span class="hljs-keyword">const</span> intercalate = curry(<span class="hljs-function">(<span class="hljs-params">sep, arr</span>) =&gt;</span> arr.join(sep));

<span class="hljs-keyword">const</span> formatInitials = compose(
  intercalate(<span class="hljs-string">"\n"</span>),
  map(formatInitial),
  map(first)
);

<span class="hljs-keyword">const</span> employees = [<span class="hljs-string">"Yann"</span>, <span class="hljs-string">"Brigitte"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"William"</span>];

<span class="hljs-keyword">const</span> initials = formatInitials(employees);
<span class="hljs-comment">// Y.</span>
<span class="hljs-comment">// B.</span>
<span class="hljs-comment">// J.</span>
<span class="hljs-comment">// W.</span>
</code></pre>
<p>So clean!</p>
<p>Like I said, <code>compose</code> makes a pipeline with the functions we give it, calling them from right to left.</p>
<p>So let's visualize what happens when <code>formatInitials(employees)</code> is parsed:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/compose-1.png" alt="compose pipeline" width="600" height="400" loading="lazy"></p>
<p>Personally, I prefer when it goes from left to right, because when writing the function, I like to think about what transformation to apply first, write it down, then repeat until the end of the pipeline.</p>
<p>Whereas with <code>compose</code>, I have to step back to write the next transformation. That just breaks the flow of my thinking.</p>
<p>Fortunately, it's not complicated to tweak it in order to go from left to right.</p>
<p>We just have to get rid of the <code>.reverse()</code> part.</p>
<p>Let's call our new helper <code>pipe</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> pipe = <span class="hljs-function">(<span class="hljs-params">...fns</span>) =&gt;</span> fns.reduce(<span class="hljs-function">(<span class="hljs-params">fn1, fn2</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> f2(f1(...args)));
</code></pre>
<p>So if we refactor the previous snippet, we get:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> formatInitials = pipe(map(first), map(formatInitial), intercalate(<span class="hljs-string">"\n"</span>));
</code></pre>
<p>For the visualization, same thing as <code>compose</code> but in reverse order:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/pipe.png" alt="pipe pipeline" width="600" height="400" loading="lazy"></p>
<h2 id="heading-hindley-milner-type-signatures">Hindley-Milner type signatures</h2>
<p>As you know, a complete program ends up with quite a few functions.</p>
<p>When you plunge back into a project after several weeks, you don't have the context to easily understand what each function does.</p>
<p>To counter that, you reread only the parts you need. But this can be quite tedious.</p>
<p>It would be nice to have a quick and powerful way to document your functions and explain what they do at a glance.</p>
<p>That's where type signatures come in. They are a way to document how a function operates and its inputs and outputs.</p>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ↓ function name</span>
<span class="hljs-comment">//                  ↓ input</span>
<span class="hljs-comment">//                            ↓ output</span>
<span class="hljs-comment">// formatInitial :: String -&gt; String</span>
<span class="hljs-keyword">const</span> formatInitial = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x.toUpperCase() + <span class="hljs-string">"."</span>;
</code></pre>
<p>Here we see that <code>formatInitial</code> takes a <code>String</code> and returns a <code>String</code>.</p>
<p>We don't care about the implementation.</p>
<p>Let's look at another example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// first :: [a] -&gt; a</span>
<span class="hljs-keyword">const</span> first = <span class="hljs-function">(<span class="hljs-params">xs</span>) =&gt;</span> xs[<span class="hljs-number">0</span>];
</code></pre>
<p>Types can be expressed with variables (usually <code>a</code>, <code>b</code>, etc.) and the brackets means "an array of" whatever is inside.</p>
<p>So we could literally read this signature like this:</p>
<p><code>first</code> takes an array of <code>a</code> and returns an <code>a</code>, where <code>a</code> can be of any type.</p>
<p>But because the type taken as input is the same as the one returned as output, we use the same variable.</p>
<p>If the output had another type, we would have used <code>b</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// imaginaryFunction :: a -&gt; b</span>
</code></pre>
<p>Warning!</p>
<p>That doesn't ensure that <code>a</code> and <code>b</code> are different types. They still can be the same.</p>
<p>Finally, let's see the case of <code>intercalate</code> which is a bit more complex:</p>
<pre><code class="lang-js"><span class="hljs-comment">// intercalate :: String -&gt; [a] -&gt; String</span>
<span class="hljs-keyword">const</span> intercalate = curry(<span class="hljs-function">(<span class="hljs-params">sep, arr</span>) =&gt;</span> arr.join(sep));
</code></pre>
<p>OK, here there are 2 arrows, which can be replaced by "returns...".</p>
<p>They indicate functions.</p>
<p>So <code>intercalate</code> takes a <code>String</code> then returns a function which takes an array of <code>a</code>, which returns a <code>String</code>.</p>
<p>Wow, that's hard to keep track of.</p>
<p>We could have written the signature like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// intercalate :: String -&gt; ([a] -&gt; String)</span>
</code></pre>
<p>Now it's more obvious that it first returns a function, which is in parentheses here. And then that function will take <code>[a]</code> as input and return <code>String</code>.</p>
<p>But we usually don't use them for clarity sake. Basically, if you stumble upon a signature of the form:</p>
<pre><code class="lang-js"><span class="hljs-comment">// imaginaryFunction :: a -&gt; b -&gt; c -&gt; d -&gt; e</span>

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

<span class="hljs-comment">// imaginaryFunction :: a -&gt; (b -&gt; (c -&gt; (d -&gt; e)))</span>

<span class="hljs-comment">// ...you see how parens nesting affects readability</span>
</code></pre>
<p><code>e</code>, the type on the right side, is the output.</p>
<p>And everything before are inputs given one-by-one, which indicates that the function is curried.</p>
<p>Nowadays, we usually have type systems like TypeScript or Flow, and the IDE is able to give us the type signature of a function when we hover over its name. Thus, it might be unnecessary to write them as comments in your code.</p>
<p>But this remains a nice tool to have in your toolkit because a lot of functional libraries out there use these type signatures in their documentations. And idiomatic functional languages (like Haskell) use them heavily.</p>
<p>So if you give them a shot, you will hopefully not be completely lost.</p>
<p>Pat yourself on the back for having read this far.</p>
<p>You should now have the ability to work with higher-order functions. Higher-order functions are simply functions that take functions as inputs and/or return them.</p>
<p>Indeed, that's exactly what we did.</p>
<p>For example, <code>curry</code> is an higher-order function because it takes a function as input and returns one as output.</p>
<p><code>compose</code>, <code>pipe</code>, <code>map</code>, and <code>reduce</code> are all higher-order functions because they take at least one function as input.</p>
<p>They are pretty cool because they allow to create very powerful abstractions.</p>
<p>Enough nattering. Let's get some practice.</p>
<h3 id="heading-exercises-set-2">Exercises (Set 2)</h3>
<ol>
<li>Given a string of the form:</li>
</ol>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> input = <span class="hljs-string">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</span>;
</code></pre>
<p>...and these helpers:</p>
<pre><code class="lang-js"><span class="hljs-comment">// filter :: (a -&gt; Boolean) -&gt; [a] -&gt; [a]</span>
<span class="hljs-keyword">const</span> filter = curry(<span class="hljs-function">(<span class="hljs-params">fn, arr</span>) =&gt;</span> arr.filter(fn));

<span class="hljs-comment">// removeDuplicates :: [a] -&gt; [a]</span>
<span class="hljs-keyword">const</span> removeDuplicates = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span> <span class="hljs-built_in">Array</span>.from(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>(arr));

<span class="hljs-comment">// getChars :: String -&gt; [Character]</span>
<span class="hljs-keyword">const</span> getChars = <span class="hljs-function">(<span class="hljs-params">str</span>) =&gt;</span> str.split(<span class="hljs-string">""</span>);

<span class="hljs-comment">// lowercase :: String -&gt; String</span>
<span class="hljs-keyword">const</span> lowercase = <span class="hljs-function">(<span class="hljs-params">str</span>) =&gt;</span> str.toLowerCase();

<span class="hljs-comment">// sort :: [a] -&gt; [a]</span>
<span class="hljs-keyword">const</span> sort = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span> [...arr].sort();
</code></pre>
<p>Create a function <code>getLetters</code> that returns all the letters in a string without duplicates, in alphabetical order, and in lowercase.</p>
<p>The goal is to use <code>compose</code> and/or <code>pipe</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// getLetters :: String -&gt; [Character]</span>
<span class="hljs-keyword">const</span> getLetters = ...
</code></pre>
<p>Note: You may have to create intermediate functions before the final one.</p>
<ol start="2">
<li>Imagine you have an object with groups' names as keys and arrays of objects representing people as values:</li>
</ol>
<pre><code class="lang-js">{
  <span class="hljs-string">"groupName"</span>: [
    {<span class="hljs-attr">firstname</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Doe"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">35</span>, <span class="hljs-attr">sex</span>: <span class="hljs-string">"M"</span>},
    {<span class="hljs-attr">firstname</span>: <span class="hljs-string">"Maria"</span>, <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Talinski"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">28</span>, <span class="hljs-attr">sex</span>: <span class="hljs-string">"F"</span>},
    <span class="hljs-comment">// ...</span>
  ],
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>Create a function that returns an object of the form:</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"groupName"</span>: {
    <span class="hljs-string">"medianAgeM"</span>: <span class="hljs-number">34</span>,
    <span class="hljs-string">"medianAgeF"</span>: <span class="hljs-number">38</span>,
  },
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>Where <code>medianAgeM</code> is the median age of men in the group and <code>medianAgeF</code> the one of women.</p>
<p>Here's some helpers:</p>
<pre><code class="lang-js"><span class="hljs-comment">// map :: (a -&gt; b) -&gt; [a] -&gt; [b]</span>
<span class="hljs-keyword">const</span> map = curry(<span class="hljs-function">(<span class="hljs-params">fn, arr</span>) =&gt;</span> arr.map(fn));

<span class="hljs-comment">// getEntries :: Object -&gt; [[Key, Val]]</span>
<span class="hljs-keyword">const</span> getEntries = <span class="hljs-function">(<span class="hljs-params">o</span>) =&gt;</span> <span class="hljs-built_in">Object</span>.entries(o);

<span class="hljs-comment">// fromEntries:: [[Key, Val]] -&gt; Object</span>
<span class="hljs-keyword">const</span> fromEntries = <span class="hljs-function">(<span class="hljs-params">entries</span>) =&gt;</span> <span class="hljs-built_in">Object</span>.fromEntries(entries);

<span class="hljs-comment">// mean :: Number -&gt; Number -&gt; Number</span>
<span class="hljs-keyword">const</span> mean = curry(<span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> <span class="hljs-built_in">Math</span>.round((x + y) / <span class="hljs-number">2</span>));

<span class="hljs-comment">// reduceOverVal :: (b -&gt; a -&gt; b) -&gt; b -&gt; [Key, [a]] -&gt; [Key, b]</span>
<span class="hljs-keyword">const</span> reduceOverVal = curry(<span class="hljs-function">(<span class="hljs-params">fn, initVal, entry</span>) =&gt;</span> [
  entry[<span class="hljs-number">0</span>],
  entry[<span class="hljs-number">1</span>].reduce(fn, initVal),
]);
</code></pre>
<p>You may have to create intermediate functions before the final one, and like before, try to use <code>compose</code> and <code>pipe</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// groupsMedianAges :: Object -&gt; Object</span>
<span class="hljs-keyword">const</span> groupsMedianAges = ...
</code></pre>
<ol start="3">
<li>Find the type signature of <code>reduce</code>:</li>
</ol>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> reduce = curry(<span class="hljs-function">(<span class="hljs-params">fn, initVal, arr</span>) =&gt;</span> arr.reduce(fn, initVal));
</code></pre>
<ol start="4">
<li>Find the type signature of <code>curry</code>:</li>
</ol>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> curry = <span class="hljs-function">(<span class="hljs-params">fn, arity = fn.length</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nextCurried</span>(<span class="hljs-params">prevArgs</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">curried</span>(<span class="hljs-params">...nextArgs</span>) </span>{
      <span class="hljs-keyword">const</span> args = [...prevArgs, ...nextArgs];

      <span class="hljs-keyword">return</span> args.length &lt; arity ? nextCurried(args) : fn(...args);
    };
  })([]);
};
</code></pre>
<p><a target="_blank" href="https://www.freecodecamp.org/news/the-principles-of-functional-programming/#set-2">Check answers</a>.</p>
<h2 id="heading-working-with-boxes-from-functors-to-monads">Working with boxes: From Functors to Monads</h2>
<p>You may already be stressed out by the title of this section. You might be thinking, "What the heck are 'Functors' and 'Monads'?"</p>
<p>Or maybe you've heard about monads because they're famously "difficult" to understand.</p>
<p>Unfortunately, I can't predict that you will definitely understand these concepts, or effectively apply them in whatever work you do.</p>
<p>In fact, if I talk about them at the end of this tutorial, it's because I think they're very powerful tools that we don't need very often.</p>
<p>Here's the reassuring part: Like anything in the world, they're not magic.</p>
<p>They follow the same rules of physics (and more specifically computer science and math) as everything else. </p>
<p>So at the end of the day, they're understandable. It just requires the right amount of time and energy.</p>
<p>In addition, they essentially build upon what we've previously talked about: types, mapping and composition.</p>
<p>Now, find that tube of <em>perseverance</em> in your toolkit and let's get started.</p>
<h3 id="heading-why-use-boxes">Why use boxes?</h3>
<p>We want to make our program with pure functions. Then we use composition to specify in which order to run them over the data.</p>
<p>However, how do we deal with <code>null</code> or <code>undefined</code>? How do we deal with exceptions? </p>
<p>Also, how do we manage side-effects without losing control, because one day we'll need to perform them?</p>
<p>The first two cases involve branching. Either the value is <code>null</code> and we do this, or we do that. Either there's an error and we do this, or a success and we do that.</p>
<p>The usual way to deal with branching is control flow.</p>
<p>However, control flow is imperative. It describes "how" the code operates.</p>
<p>So functional programmers came up with the idea of using a box that contains one of two possible values.</p>
<p>We use that box as input/output to functions regardless of what's inside.</p>
<p>But because those boxes also have specific behaviors that abstract function application, we can apply a function over a box and it will decide how to actually perform it depending on its inner value.</p>
<p>Thus, we don't have to adapt our functions to the data. We don't have to clutter them with logic that doesn't belong to.</p>
<p>Things like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFunc = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> {
  <span class="hljs-comment">// ...</span>
  <span class="hljs-keyword">if</span> (x !== <span class="hljs-literal">null</span>) {
    <span class="hljs-comment">// ...</span>
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// ...</span>
  }
};
</code></pre>
<p>With that, we can implement branching (and other stuff) while using only functions and preserve composition.</p>
<p>The boxes we'll see, named <strong>Algebraic Data Types</strong> (ADT), enable us to do more while keeping the data and the functions separate.</p>
<p>Functors and monads are indeed Algebraic Data Types.</p>
<h3 id="heading-functors">Functors</h3>
<p>Functors are containers/data structures/types that hold data along with a <code>map</code> method.</p>
<p>This <code>map</code> method allow us to apply a function on the value(s) contained in the functor. What's returned is the same functor but containing the result of the function call.</p>
<p>Let's introduce <code>Identity</code>, the simplest functor:</p>
<p>We could implement it with a class, but I'll use regular functions here:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Identity = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> ({
  <span class="hljs-attr">inspect</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-string">`Identity(<span class="hljs-subst">${x}</span>)`</span>,
  <span class="hljs-attr">map</span>: <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> Identity(fn(x)),
  <span class="hljs-attr">value</span>: x,
});

<span class="hljs-comment">// add5 :: Number -&gt; Number</span>
<span class="hljs-keyword">const</span> add5 = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x + <span class="hljs-number">5</span>;

<span class="hljs-keyword">const</span> myFirstFunctor = Identity(<span class="hljs-number">1</span>);

myFirstFunctor.map(add5);
<span class="hljs-comment">// Identity(6)</span>
</code></pre>
<p>You see? Not that complicated!</p>
<p><code>Identity</code> is the equivalent of the <code>identity</code> function but in the world of functors.</p>
<p><code>identity</code> is a well-known function in FP that may seem useless at first sight:</p>
<pre><code class="lang-js"><span class="hljs-comment">// identity :: a -&gt; a</span>
<span class="hljs-keyword">const</span> identity = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x;
</code></pre>
<p>It does nothing on the data, just returns it as is.</p>
<p>But it can be useful when doing stuff like composition because sometimes, you don't want to do anything with the data, just pass it through.</p>
<p>And because composition works with functions and not raw values, you need to wrap them into the <code>identity</code> function.</p>
<p><code>Identity</code> serves the same purpose but when composing functors.</p>
<p>More on that later.</p>
<p>Returning back to the previous snippet, we could have done <code>map(add5, 1)</code> and it would have given us the same result apart from the fact that there would not have been a container around it.</p>
<p>So there's no extra feature here.</p>
<p>Now let's see another functor called <code>Maybe</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Nothing = <span class="hljs-function">() =&gt;</span> ({
  <span class="hljs-attr">inspect</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-string">`Nothing()`</span>,
  <span class="hljs-attr">map</span>: Nothing,
});

<span class="hljs-keyword">const</span> Maybe = { Just, Nothing };

<span class="hljs-comment">// Just is equivalent to Identity</span>
</code></pre>
<p><code>Maybe</code> is a mix of 2 functors, <code>Just</code> and <code>Nothing</code>.</p>
<p><code>Nothing</code> contains, well, nothing. But it's still a functor so we can use it wherever we need functors.</p>
<p><code>Maybe</code>, like its name suggests, <em>may</em> contain a value (<code>Just</code>) or not (<code>Nothing</code>).</p>
<p>Now how would we use it?</p>
<p>Most of the time, it's used in functions that can return <code>null</code> or <code>undefined</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// isNothing :: a -&gt; Boolean</span>
<span class="hljs-keyword">const</span> isNothing = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x === <span class="hljs-literal">null</span> || x === <span class="hljs-literal">undefined</span>;

<span class="hljs-comment">// safeProp :: String -&gt; Object -&gt; Maybe a</span>
<span class="hljs-keyword">const</span> safeProp = curry(<span class="hljs-function">(<span class="hljs-params">prop, obj</span>) =&gt;</span>
  isNothing(obj[prop]) ? Maybe.Nothing() : Maybe.Just(obj[prop])
);

<span class="hljs-keyword">const</span> o = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> };

<span class="hljs-keyword">const</span> a = safeProp(<span class="hljs-string">"a"</span>, o);
<span class="hljs-comment">// Just(1)</span>

<span class="hljs-keyword">const</span> b = safeProp(<span class="hljs-string">"b"</span>, o);
<span class="hljs-comment">// Nothing</span>

a.map(add5);
<span class="hljs-comment">// Just(6)</span>

b.map(add5);
<span class="hljs-comment">// Nothing</span>
</code></pre>
<p>Do you see were the power of <code>Maybe</code> lies?</p>
<p>You can safely apply a function on the inner value within whatever functor <code>safeProp</code> returns, you will not get an unexpected <code>NaN</code> result because you added a number with <code>null</code> or <code>undefined</code>.</p>
<p>Thanks to the <code>Nothing</code> functor, the function mapped will not be called at all.</p>
<p>However, <code>Maybe</code> implementations often cheat a little bit by doing the <code>isNothing</code> check inside the monad, whereas a strictly pure monad shouldn't:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Maybe = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> ({
  <span class="hljs-attr">map</span>: <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> (x === <span class="hljs-literal">null</span> || x === <span class="hljs-literal">undefined</span> ? Maybe(x) : Maybe(fn(x))),
  <span class="hljs-attr">inspect</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-string">`Maybe(<span class="hljs-subst">${x}</span>)`</span>,
  <span class="hljs-attr">value</span>: x,
});

<span class="hljs-comment">// safeProp :: String -&gt; Object -&gt; Maybe a</span>
<span class="hljs-keyword">const</span> safeProp = curry(<span class="hljs-function">(<span class="hljs-params">prop, obj</span>) =&gt;</span> Maybe(obj[prop]));

<span class="hljs-keyword">const</span> o = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> };

<span class="hljs-keyword">const</span> c = safeProp(<span class="hljs-string">"a"</span>, o);
<span class="hljs-comment">// Maybe(1)</span>

<span class="hljs-keyword">const</span> d = safeProp(<span class="hljs-string">"b"</span>, o);
<span class="hljs-comment">// Maybe(undefined)</span>

c.map(add5);
<span class="hljs-comment">// Maybe(6)</span>

d.map(add5);
<span class="hljs-comment">// Maybe(undefined)</span>
</code></pre>
<p>The advantage of having these functors is that, to be called "functors", they must implement a specific interface, in this case <code>map</code>.</p>
<p>Thus, each type of functor has unique features while having capabilities shared by all functors, which make them predictable.</p>
<p>When using <code>Maybe</code> in real cases, we eventually need to do something with the data to release the value.</p>
<p>In addition, if the operations took the unwanted branch and fails, we'll get <code>Nothing</code>.</p>
<p>Let's imagine we want to print the value retrieved from <code>o</code> in our previous example.</p>
<p>We might want to print something more useful to the user than <code>"Nothing"</code> if the operation failed.</p>
<p>So for releasing the value and provide a fallback if we get <code>Nothing</code>, we have a little helper called <code>maybe</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// maybe :: c -&gt; (a -&gt; b) -&gt; Maybe a -&gt; b | c</span>
<span class="hljs-keyword">const</span> maybe = curry(<span class="hljs-function">(<span class="hljs-params">fallbackVal, fn, maybeFunctor</span>) =&gt;</span>
  maybeFunctor.val === <span class="hljs-literal">undefined</span> ? fallbackVal : fn(maybeFunctor.val)
);

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

<span class="hljs-keyword">const</span> o = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> };

<span class="hljs-keyword">const</span> printVal1 = pipe(
  safeProp(<span class="hljs-string">"a"</span>),
  maybe(<span class="hljs-string">"Failure to retrieve the value."</span>, add5),
  <span class="hljs-built_in">console</span>.log
);

<span class="hljs-keyword">const</span> printVal2 = pipe(
  safeProp(<span class="hljs-string">"b"</span>),
  maybe(<span class="hljs-string">"Failure to retrieve the value."</span>, add5),
  <span class="hljs-built_in">console</span>.log
);

printVal1(o);
<span class="hljs-comment">// console: 6</span>
printVal2(o);
<span class="hljs-comment">// console: "Failure to retrieve the value."</span>
</code></pre>
<p>Great!</p>
<p>If this is the first time you've been exposed to this concept, that might seem unclear and unfamiliar.</p>
<p>But actually, it's something you're already familiar with.</p>
<p>If you're familiar with JavaScript, chances are that you've used the built-in <code>map</code>:</p>
<pre><code class="lang-js">[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>].map(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x * <span class="hljs-number">2</span>);
<span class="hljs-comment">// [2, 4, 6]</span>
</code></pre>
<p>Well, remember the definition of a functor. It's a data structure that has a <code>map</code> method.</p>
<p>Now look at the previous snippet: what's the data structure that has a <code>map</code> method here?</p>
<p>The <code>Array</code>! The native <code>Array</code> type in JavaScript is a functor!</p>
<p>Its specialty is that it can contain multiple values. But the essence of <code>map</code> stays the same: it takes a value as input and returns/maps it to an output.</p>
<p>So in this case, the mapper function runs for each value.</p>
<p>Cool!</p>
<p>Now that we know what's a functor, let's move on to extend its interface.</p>
<h3 id="heading-pointed">Pointed</h3>
<p>A pointed functor is one that has an <code>of</code> (aka <code>pure</code>, <code>unit</code>) method.</p>
<p>So with <code>Maybe</code> that gives us:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Maybe = {Just, Nothing, <span class="hljs-attr">of</span>: Just};
</code></pre>
<p><code>of</code> is meant to place a given value into the <strong>default minimum context</strong> of the functor.</p>
<p>You may ask:</p>
<blockquote>
<p>Why <code>Just</code> and not <code>Nothing</code> ?</p>
</blockquote>
<p>When using <code>of</code>, we expect to be able to map right away.</p>
<p>If we use <code>Nothing</code>, it would ignore everything we map.</p>
<p><code>of</code> expects you to insert a "successful" value.</p>
<p>Thus, you can still shoot yourself in the foot by inserting <code>undefined</code>, for example, and then map a function that doesn't expect this value:</p>
<pre><code class="lang-js">Maybe.of(<span class="hljs-literal">undefined</span>).map(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x + <span class="hljs-number">1</span>);
<span class="hljs-comment">// Just(NaN)</span>
</code></pre>
<p>Let's introduce another functor to better understand when it's useful:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> IO = <span class="hljs-function">(<span class="hljs-params">dangerousFn</span>) =&gt;</span> ({
  <span class="hljs-attr">inspect</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-string">`IO(?)`</span>,
  <span class="hljs-attr">map</span>: <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> IO(<span class="hljs-function">() =&gt;</span> fn(dangerousFn())),
});

IO.of = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> IO(<span class="hljs-function">() =&gt;</span> x);
</code></pre>
<p>Unlike <code>Just</code>, <code>IO</code> don't get a value as is but needs it wrapped in a function.</p>
<p>Why is that?</p>
<p><em>I/O</em> stands for <em>Input/Output</em>.</p>
<p>The term is used to describe any program, operation, or device that transfers data to or from a computer and to or from a peripheral device.</p>
<p>So it's intended to be used for input/output operations, which are side-effects because they rely on/affect the outside world.</p>
<p>Querying the DOM is an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// getEl :: String -&gt; DOM</span>
<span class="hljs-keyword">const</span> getEl = <span class="hljs-function">(<span class="hljs-params">sel</span>) =&gt;</span> <span class="hljs-built_in">document</span>.querySelector(sel);
</code></pre>
<p>This function is impure because given a same input, it can return different outputs:</p>
<pre><code class="lang-js">getEl(<span class="hljs-string">"#root"</span>);
<span class="hljs-comment">// &lt;div id="root"&gt;&lt;/div&gt;</span>

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

getEl(<span class="hljs-string">"#root"</span>);
<span class="hljs-comment">// &lt;div id="root"&gt;There's text now !&lt;/div&gt;</span>

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

getEl(<span class="hljs-string">"#root"</span>);
<span class="hljs-comment">// null</span>
</code></pre>
<p>Whereas by inserting an intermediate function, <code>getEl</code> returns always the same output:</p>
<pre><code class="lang-js"><span class="hljs-comment">// getEl :: String -&gt; _ -&gt; DOM</span>
<span class="hljs-keyword">const</span> getEl = <span class="hljs-function">(<span class="hljs-params">sel</span>) =&gt;</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">document</span>.querySelector(sel);

getEl(<span class="hljs-string">"#root"</span>);
<span class="hljs-comment">// function...</span>
</code></pre>
<p>Whatever the argument passed is, <code>getEl</code> will always return a function, allowing it to be pure.</p>
<p>However, we're not magically erasing the effect because now, it's the returned function that's impure.</p>
<p>We get purity out of laziness.</p>
<p>The outer function only serves as a protective box that we can pass around safely. When we are ready to release the effect, we call the returned function's function.</p>
<p>And because we want to be careful doing so, we name the function <code>unsafePerformIO</code> to remind the programmer that it's dangerous.</p>
<p>Until then, we can do our mapping and composition stuff peacefully.</p>
<p>So that's the mechanism used by <code>IO</code>.</p>
<p>If you pass a value directly to it, it must be a function with the same signature as the one that <code>getEl</code> returns:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = IO(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#root"</span>));

<span class="hljs-comment">// and not:</span>

<span class="hljs-keyword">const</span> invalid = IO(<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#root"</span>));
</code></pre>
<p>But as you can imagine, it quickly becomes tedious to always wrap our value in a function before passing it into <code>IO</code>.</p>
<p>Here's where <code>of</code> shines – it will do that for us:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> betterNow = IO.of(<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#root"</span>));
</code></pre>
<p>That's what I meant by <strong>default minimum context</strong>.</p>
<p>In the case of <code>IO</code>, it's wrapping the raw value in a function. But it can be something else, it depends of the functor in question.</p>
<h3 id="heading-exercises-set-3">Exercises (Set 3)</h3>
<ol>
<li>Write a function <code>uppercaseF</code> that uppercase a string inside a functor:</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// uppercaseF :: Functor F =&gt; F String -&gt; F String</span>
<span class="hljs-keyword">const</span> uppercaseF = ...
</code></pre>
<ol start="2">
<li>Use the <code>uppercaseF</code> function you previously built, <code>maybe</code>, and <code>safeProp</code> to create a function that retrieves the name of a user and prints an uppercased version of it.</li>
</ol>
<p>The user object has this form:</p>
<pre><code class="lang-js">{
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Yann Salmon"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">18</span>,
  <span class="hljs-attr">interests</span>: [<span class="hljs-string">"Programming"</span>, <span class="hljs-string">"Sport"</span>, <span class="hljs-string">"Reading"</span>, <span class="hljs-string">"Math"</span>],
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// safeProp :: String -&gt; Object -&gt; Maybe a</span>

<span class="hljs-comment">// maybe :: c -&gt; (a -&gt; b) -&gt; Maybe a -&gt; b | c</span>

<span class="hljs-comment">// printUsername :: User -&gt; _</span>
<span class="hljs-keyword">const</span> printUsername = ...
</code></pre>
<p><a target="_blank" href="https://www.freecodecamp.org/news/the-principles-of-functional-programming/#set-3">Check answers</a>.</p>
<h3 id="heading-applicatives">Applicatives</h3>
<p>If you work with functors, you will stumble upon situations where you have multiple functors containing values on which you would like to apply a function:</p>
<pre><code class="lang-js"><span class="hljs-comment">// concatStr :: String -&gt; String -&gt; String</span>
<span class="hljs-keyword">const</span> concatStr = curry(<span class="hljs-function">(<span class="hljs-params">str1, str2</span>) =&gt;</span> str1 + str2);

<span class="hljs-keyword">const</span> a = Identity(<span class="hljs-string">"Hello"</span>);

<span class="hljs-keyword">const</span> b = Identity(<span class="hljs-string">" world !"</span>);
</code></pre>
<p>Unfortunately, we can't pass functors as arguments to <code>concatStr</code> because it expects strings.</p>
<p>The <code>Applicative</code> interface solves that problem.</p>
<p>A functor that implements it is one that implements an <code>ap</code> method. <code>ap</code> takes a functor as argument and returns a functor of the same type.</p>
<p>Within the returned functor, there will be the result of mapping the value of the functor <code>ap</code> was called on, over the value of the functor previously taken as argument.</p>
<p>I know that's a lot to digest. Take some time and let that sink in.</p>
<p>Let's continue our previous snippet to see it in action:</p>
<pre><code class="lang-js"><span class="hljs-comment">// concatStr :: String -&gt; String -&gt; String</span>
<span class="hljs-keyword">const</span> concatStr = curry(<span class="hljs-function">(<span class="hljs-params">str1, str2</span>) =&gt;</span> str1 + str2);

<span class="hljs-keyword">const</span> a = Identity(<span class="hljs-string">"Hello"</span>);

<span class="hljs-keyword">const</span> b = Identity(<span class="hljs-string">" world !"</span>);

<span class="hljs-keyword">const</span> c = a.map(concatStr);
<span class="hljs-comment">// Identity(concatStr("Hello", _))</span>

<span class="hljs-keyword">const</span> result = c.ap(b);
<span class="hljs-comment">// Identity("Hello world !")</span>
</code></pre>
<p>First, we map <code>concatStr</code> over <code>a</code>. What happens is that <code>concatStr("Hello")</code> is called and becomes the inner value of <code>c</code>, still an <code>Identity</code> functor.</p>
<p>And remember, what does return <code>concatStr("Hello")</code>? Another function that waits for the remaining arguments!</p>
<p>Indeed, <code>concatStr</code> is curried.</p>
<p>Note that currying is necessary in order to use this technique.</p>
<p>Then, like I said, <code>ap</code> maps the value of the functor it's called on (in this case <code>c</code>, so it maps <code>concatStr("Hello")</code>) over the value of the functor taken as argument (here it's <code>b</code> containing <code>" world !"</code>).</p>
<p>So <code>result</code> ends up being an <code>Identity</code> functor (same type as <code>b</code>) containing the result of <code>concatStr("Hello")(" world !")</code>, that is <code>"Hello world !"</code>!</p>
<p>Here's the implementation:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Identity = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> ({
  <span class="hljs-attr">inspect</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-string">`Identity(<span class="hljs-subst">${x}</span>)`</span>,
  <span class="hljs-comment">// Functor interface</span>
  <span class="hljs-attr">map</span>: <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> Identity(fn(x)),
  <span class="hljs-comment">// Applicative interface</span>
  <span class="hljs-attr">ap</span>: <span class="hljs-function">(<span class="hljs-params">functor</span>) =&gt;</span> functor.map(x),
  <span class="hljs-attr">value</span>: x,
});

<span class="hljs-comment">// Pointed interface</span>
Identity.of = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> Identity(x);
</code></pre>
<p>As you can see, the functor <code>ap</code> is called on must contain a function. Otherwise it wouldn't work. In our previous example, that was the <code>c</code> step.</p>
<p>If we inline everything, we get:</p>
<pre><code class="lang-js"><span class="hljs-comment">// concatStr :: String -&gt; String -&gt; String</span>
<span class="hljs-keyword">const</span> concatStr = curry(<span class="hljs-function">(<span class="hljs-params">str1, str2</span>) =&gt;</span> str1 + str2);

<span class="hljs-keyword">const</span> result = Identity(<span class="hljs-string">"Hello"</span>).map(concatStr).ap(Identity(<span class="hljs-string">" world !"</span>));
<span class="hljs-comment">// Identity("Hello world !")</span>
</code></pre>
<p>There's an interesting mathematical property about <code>ap</code>:</p>
<pre><code class="lang-js">F(x).map(fn) === F(fn).ap(F(x));
</code></pre>
<p>The left side of the equality corresponds to what we did previously.</p>
<p>So following the right side, <code>result</code> could also be written like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> result = Identity(concatStr)
  .ap(Identity(<span class="hljs-string">"Hello"</span>))
  .ap(Identity(<span class="hljs-string">" world !"</span>));
</code></pre>
<p>Take the time to reread if you feel overwhelmed.</p>
<p>The latter version ressembles more to a regular function call than the previous. We're feeding <code>concatStr</code> with its arguments in a left-to-right manner:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/applicatives.png" alt="Chain of Applicative functors" width="600" height="400" loading="lazy"></p>
<p>And all of that happens inside our protecting container.</p>
<p>Finally, we can further clean up this process with parametrization.</p>
<p>A function called <code>liftA2</code> do that:</p>
<pre><code class="lang-js"><span class="hljs-comment">// liftA2 :: Apply functor F =&gt; (a -&gt; b -&gt; c) -&gt; F a -&gt; F b -&gt; F c</span>
<span class="hljs-keyword">const</span> liftA2 = curry(<span class="hljs-function">(<span class="hljs-params">fn, F1, F2</span>) =&gt;</span> F1.map(fn).ap(F2));

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

<span class="hljs-keyword">const</span> result = liftA2(concatStr, Identity(<span class="hljs-string">"Hello"</span>), Identity(<span class="hljs-string">" world !"</span>));
</code></pre>
<p>I'm sure we can agree that this name is really awkward.</p>
<p>I guess it made sense for the pioneers of Functional Programming, who were probably "math" people.</p>
<p>But anyway, you can think of it as "lifting" a function and its arguments, then putting them into a functor in order to <code>ap</code> each one on the other.</p>
<p>However, this metaphor is just partially true because arguments are already given within their container.</p>
<p>The interesting part is the body of the function.</p>
<p>You can notice that it uses the left-hand side of the mathematical property we saw earlier.</p>
<p>If we implement it using the right-hand side, we need to know what type of functor <code>F1</code> and <code>F2</code> are because we need to wrap the function with the same:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> liftA2 = curry(<span class="hljs-function">(<span class="hljs-params">fn, F1, F2</span>) =&gt;</span> F(fn).ap(F1).ap(F2));
<span class="hljs-comment">//                                   ↑ what's F ? We need the precise constructor.</span>
</code></pre>
<p>So by using the left version, we abstract the functor type for free.</p>
<p>Now you might think, "OK, but what if the function requires 3, 4, or more arguments?"</p>
<p>If that's the case, you can build variants just by extending our previous <code>liftA2</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// liftA3 :: Apply functor F =&gt; (a -&gt; b -&gt; c -&gt; d) -&gt; F a -&gt; F b -&gt; F c -&gt; F d</span>
<span class="hljs-keyword">const</span> liftA3 = curry(<span class="hljs-function">(<span class="hljs-params">fn, F1, F2, F3</span>) =&gt;</span> F1.map(fn).ap(F2).ap(F3));

<span class="hljs-comment">// liftA4 :: Apply functor F =&gt; (a -&gt; b -&gt; c -&gt; d -&gt; e) -&gt; F a -&gt; F b -&gt; F c -&gt; F d -&gt; F e</span>
<span class="hljs-keyword">const</span> liftA4 = curry(<span class="hljs-function">(<span class="hljs-params">fn, F1, F2, F3, F4</span>) =&gt;</span> F1.map(fn).ap(F2).ap(F3).ap(F4));

<span class="hljs-comment">// take3Args :: String -&gt; String -&gt; Number -&gt; String</span>
<span class="hljs-keyword">const</span> take3Args = curry(
  <span class="hljs-function">(<span class="hljs-params">firstname, lastname, age</span>) =&gt;</span>
    <span class="hljs-string">`My name is <span class="hljs-subst">${firstname}</span> <span class="hljs-subst">${lastname}</span> and I'm <span class="hljs-subst">${age}</span>.`</span>
);

<span class="hljs-comment">// take4Args :: a -&gt; b -&gt; c -&gt; d -&gt; [a, b, c, d]</span>
<span class="hljs-keyword">const</span> take4Args = curry(<span class="hljs-function">(<span class="hljs-params">a, b, c, d</span>) =&gt;</span> [a, b, c, d]);

liftA3(take3Args, Identity(<span class="hljs-string">"Yann"</span>), Identity(<span class="hljs-string">"Salmon"</span>), Identity(<span class="hljs-number">18</span>));
<span class="hljs-comment">// Identity("My name is Yann Salmon and I'm 18.")</span>

liftA4(take4Args, Identity(<span class="hljs-number">1</span>), Identity(<span class="hljs-number">2</span>), Identity(<span class="hljs-number">3</span>), Identity(<span class="hljs-number">4</span>));
<span class="hljs-comment">// Identity([1, 2, 3, 4])</span>
</code></pre>
<p>As you can notice, <em>A*</em> refers to the number of arguments.</p>
<p>Wow! We've covered a bunch of things.</p>
<p>Again, I want to congratulate you for the time and attention you've given so far.</p>
<p>We almost have a fully fledged toolbox for resolving real world problems in a functional way.</p>
<p>We now need to explore the <code>Monad</code> interface.</p>
<h3 id="heading-exercises-set-4">Exercises (Set 4)</h3>
<p>Consider this user object for the next 2 exercises:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">id</span>: <span class="hljs-string">"012345"</span>,
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
  <span class="hljs-attr">hobbies</span>: [<span class="hljs-string">"Cycling"</span>, <span class="hljs-string">"Drawing"</span>],
  <span class="hljs-attr">friends</span>: [
    {<span class="hljs-attr">name</span>: <span class="hljs-string">"Mickael Bolp"</span>, ...},
    <span class="hljs-comment">// ...</span>
  ],
  <span class="hljs-attr">partner</span>: {<span class="hljs-attr">name</span>: <span class="hljs-string">"Theresa Doe"</span>, ...},
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<ol>
<li>Create a function that returns a phrase describing the couple if the user has a partner using the given helpers and <code>ap</code>:</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// safeProp :: String -&gt; Object -&gt; Maybe a</span>
<span class="hljs-keyword">const</span> safeProp = curry(<span class="hljs-function">(<span class="hljs-params">prop, obj</span>) =&gt;</span>
  obj[prop] === <span class="hljs-literal">undefined</span> || obj[prop] === <span class="hljs-literal">null</span>
    ? Maybe.Nothing()
    : Maybe.Just(obj[prop])
);

<span class="hljs-comment">// getCouplePresentation :: User -&gt; User -&gt; String</span>
<span class="hljs-keyword">const</span> getCouplePresentation = curry(
  <span class="hljs-function">(<span class="hljs-params">name1, name2</span>) =&gt;</span> <span class="hljs-string">`<span class="hljs-subst">${name1}</span> and <span class="hljs-subst">${name2}</span> are partners.`</span>
);

<span class="hljs-comment">// getName :: User -&gt; String</span>
<span class="hljs-keyword">const</span> getName = <span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> user.name;
<span class="hljs-comment">// I could have written: const getName = safeProp("name")</span>
<span class="hljs-comment">// but I didn't and that's intentional.</span>
<span class="hljs-comment">// We assume that a user always has a name.</span>

<span class="hljs-keyword">const</span> couple = ...
</code></pre>
<ol start="2">
<li>Refactor the previous answer using <code>liftA2</code> (check out the answer of the previous question before):</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// liftA2 :: Apply functor F =&gt; (a -&gt; b -&gt; c) -&gt; F a -&gt; F b -&gt; F c</span>
<span class="hljs-keyword">const</span> liftA2 = curry(<span class="hljs-function">(<span class="hljs-params">fn, F1, F2</span>) =&gt;</span> F1.map(fn).ap(F2));

<span class="hljs-keyword">const</span> couple = ...
</code></pre>
<p><a target="_blank" href="https://www.freecodecamp.org/news/the-principles-of-functional-programming/#set-4">Check answers</a>.</p>
<h3 id="heading-monads">Monads</h3>
<p>In the exercises just before, I gave the helper <code>getName</code> whereas we could have derived it from <code>safeProp</code>.</p>
<p>The reason I did that is because <code>safeProp</code> returns a <code>Maybe</code> functor.</p>
<p>Thus, by trying to get the partner's name of a user, we end up with 2 nested <code>Maybe</code> functors:</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> getPartnerName = pipe(safeProp(<span class="hljs-string">"partner"</span>), map(safeProp(<span class="hljs-string">"name"</span>)));
<span class="hljs-comment">// Maybe(Maybe("Theresa Doe"))</span>
</code></pre>
<p>Let's see another example where this problem get even worse:</p>
<pre><code class="lang-js"><span class="hljs-comment">// getUser :: Object -&gt; IO User</span>
<span class="hljs-keyword">const</span> getUser = <span class="hljs-function">(<span class="hljs-params">{ email, password }</span>) =&gt;</span> IO.of(db.getUser(email, password));

<span class="hljs-comment">// getLastPurchases :: User -&gt; IO [Purchase]</span>
<span class="hljs-keyword">const</span> getLastPurchases = <span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> IO.of(db.purchases(user));

<span class="hljs-comment">// display :: [Purchase] -&gt; IO _</span>
<span class="hljs-keyword">const</span> display = <span class="hljs-string">"some implementation"</span>;

<span class="hljs-comment">// displayUserPurchases :: Object -&gt; IO _</span>
<span class="hljs-keyword">const</span> displayUserPurchases = pipe(
  getUser,
  map(getLastPurchases),
  map(map(display))
);

displayUserPurchases({ <span class="hljs-attr">email</span>: <span class="hljs-string">"johndoe@whatever.com"</span>, <span class="hljs-attr">password</span>: <span class="hljs-string">"1234"</span> });
<span class="hljs-comment">// IO(IO(IO _))</span>
</code></pre>
<p>How to get rid of these layers of container that enforce us to do nested <code>map</code> that impairs readability ?</p>
<p>Monads to our rescue! Monads are functors that can flatten.</p>
<p>Again, like regular functors, you will probably not use them very often.</p>
<p>However, they're powerful abstractions that bundle a specific set of behaviors with a value. </p>
<p>They're data structures backed up by mathematical laws which make them extremely predictable and reliable.</p>
<p>In addition, laws like composition or associativity tell us that we can do the same thing while making the operations in a different way.</p>
<p>Remember what we saw with Applicatives and <code>ap</code>:</p>
<pre><code class="lang-js">F(x).map(fn) === F(fn).ap(F(x));
</code></pre>
<p>These can be helpful because certain variants might be more efficient computationaly.</p>
<p>The thing is that the way we prefer to write programs may differ from the way they should be written if we wanted them to be efficient as much as possible.</p>
<p>So because these laws ensure us that all variants do the same thing, we can write how we like and ask the compiler to use the more efficient variant later.</p>
<p>That's why I didn't bothered you with these laws very much. But be aware of their utility (which certainly extends beyond that).</p>
<p>Going back to our monads, the flattening behavior is usually implemented with a <code>chain</code> (aka <code>flatMap</code>, <code>bind</code>, <code>&gt;==</code>) method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Identity = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> ({
  <span class="hljs-attr">inspect</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-string">`Identity(<span class="hljs-subst">${x}</span>)`</span>,
  <span class="hljs-comment">// Functor interface</span>
  <span class="hljs-attr">map</span>: <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> Identity(fn(x)),
  <span class="hljs-comment">// Applicative interface</span>
  <span class="hljs-attr">ap</span>: <span class="hljs-function">(<span class="hljs-params">functor</span>) =&gt;</span> functor.map(x),
  <span class="hljs-comment">// Monad interface</span>
  <span class="hljs-attr">chain</span>: <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> fn(x),
  <span class="hljs-attr">value</span>: x,
});

<span class="hljs-comment">// Pointed interface</span>
Identity.of = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> Identity(x);

<span class="hljs-comment">// chain :: Monad M =&gt; (a -&gt; M b) -&gt; M a -&gt; M b</span>
<span class="hljs-keyword">const</span> chain = curry(<span class="hljs-function">(<span class="hljs-params">fn, monad</span>) =&gt;</span> monad.chain(fn));

<span class="hljs-keyword">const</span> getPartnerName = pipe(safeProp(<span class="hljs-string">"partner"</span>), chain(safeProp(<span class="hljs-string">"name"</span>)));
</code></pre>
<p>In the case of <code>Identity</code>, <code>chain</code> is like <code>map</code> but without a new <code>Identity</code> functor surrounding it.</p>
<p>You may think, "That defeats the purpose, we'll get back a value unboxed!"</p>
<p>But, we won't because <code>fn</code> is meant to return a functor.</p>
<p>Look at the type signature of this <code>chain</code> helper:</p>
<pre><code class="lang-js"><span class="hljs-comment">// chain :: Monad M =&gt; (a -&gt; M b) -&gt; M a -&gt; M b</span>
<span class="hljs-keyword">const</span> chain = curry(<span class="hljs-function">(<span class="hljs-params">fn, monad</span>) =&gt;</span> monad.chain(fn));
</code></pre>
<p>In fact, we could do the same by first applying the function that returns a functor, which gives us a nested one, and then removing the inner or the outer.</p>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Identity = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> ({
  <span class="hljs-comment">// ...</span>
  <span class="hljs-attr">chain</span>: <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> Identity(x).map(fn).value,
  <span class="hljs-attr">value</span>: x,
});
</code></pre>
<p>You can see that we first wrap <code>x</code>, then map, then grab the inner value.</p>
<p>Because wrapping <code>x</code> in a new <code>Identity</code> and eventually picking its inner value are opposite, it's cleaner to do none of those like in the first version.</p>
<p>Now let's refactor the fist snippet of this section (with nested functors) using the <code>chain</code> helper:</p>
<pre><code class="lang-js"><span class="hljs-comment">// BEFORE</span>
<span class="hljs-comment">// ...</span>

<span class="hljs-comment">// displayUserPurchases :: Object -&gt; IO _</span>
<span class="hljs-keyword">const</span> displayUserPurchases = pipe(
  getUser,
  map(getLastPurchases),
  map(map(display))
);

displayUserPurchases({ <span class="hljs-attr">email</span>: <span class="hljs-string">"johndoe@whatever.com"</span>, <span class="hljs-attr">password</span>: <span class="hljs-string">"1234"</span> });
<span class="hljs-comment">// IO(IO(IO _))</span>

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

<span class="hljs-keyword">const</span> displayUserPurchases = pipe(
  getUser,
  chain(getLastPurchases),
  chain(display)
);

displayUserPurchases({ <span class="hljs-attr">email</span>: <span class="hljs-string">"johndoe@whatever.com"</span>, <span class="hljs-attr">password</span>: <span class="hljs-string">"1234"</span> });
<span class="hljs-comment">// IO _</span>
</code></pre>
<p>First, <code>getUser</code> returns an <code>IO(User)</code>.</p>
<p>Then, we chain <code>getLastPurchases</code> instead of mapping it.</p>
<p>In other words, we keep the result of <code>getLastPurchases(User)</code> (which is <code>IO(?)</code>), getting rid of the original <code>IO</code> that surrounded <code>User</code>.</p>
<p>That's why monads are often compared to onions – flattening/chaining them is like removing an onion's layer. When you do it, you're releasing potential unwanted results which could make you cry ?.</p>
<p>In the last example, if the first computation <code>getUser</code> had returned <code>Nothing</code>, calling <code>chain</code> on it would have returned <code>Nothing</code> too.</p>
<p>This functor does no operation.</p>
<p>However, we need to extend the simple version we saw earlier in this post in order to give it the <code>Applicative</code> and <code>Monad</code> interfaces.</p>
<p>Otherwise, we couldn't use it as such:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Nothing = <span class="hljs-function">() =&gt;</span> ({
  <span class="hljs-attr">inspect</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-string">`Nothing()`</span>,
  <span class="hljs-attr">map</span>: Nothing,
  <span class="hljs-attr">ap</span>: Nothing,
  <span class="hljs-attr">chain</span>: Nothing,
});

Nothing.of = <span class="hljs-function">() =&gt;</span> Nothing();
</code></pre>
<p>As long as you keep at least one layer (that is one functor) until you're ready to release the effect, that's ok.</p>
<p>But if you flatten the monad to get the raw value contained within all over the place because you're not able to figure out how to compose it, that defeats the purpose.</p>
<h3 id="heading-recap">Recap</h3>
<p><strong>Functors</strong> apply a function to a wrapped value (<code>map</code>).</p>
<p><strong>Pointed</strong> functors have a method to place a value in the default minimum context of the functor (<code>of</code>).</p>
<p><strong>Applicatives</strong> apply a wrapped function to a wrapped value (<code>ap</code> + <code>of</code>).</p>
<p><strong>Monads</strong> apply a function that returns a wrapped value to a wrapped value (<code>chain</code> + <code>of</code>).</p>
<h3 id="heading-exercises-set-5">Exercises (Set 5)</h3>
<ol>
<li>Consider this object:</li>
</ol>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> restaurant = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"The Creamery"</span>,
  <span class="hljs-attr">address</span>: {
    <span class="hljs-attr">city</span>: <span class="hljs-string">"Los Angeles"</span>,
    <span class="hljs-attr">street</span>: {
      <span class="hljs-attr">name</span>: <span class="hljs-string">"Melrose Avenue"</span>,
    },
  },
  <span class="hljs-attr">rating</span>: <span class="hljs-number">8</span>,
};
</code></pre>
<p>Create a function <code>getStreetName</code> that, like the name suggests, returns the street name of the restaurant.</p>
<p>Use <code>safeProp</code> (and <code>chain</code>, along with any other functional helpers you need) to do so in a pure way.</p>
<pre><code class="lang-js"><span class="hljs-comment">// safeProp :: String -&gt; Object -&gt; Maybe a</span>
<span class="hljs-keyword">const</span> safeProp = curry(<span class="hljs-function">(<span class="hljs-params">prop, obj</span>) =&gt;</span>
  obj[prop] === <span class="hljs-literal">undefined</span> || obj[prop] === <span class="hljs-literal">null</span>
    ? Maybe.Nothing()
    : Maybe.Just(obj[prop])
);

<span class="hljs-comment">// getStreetName :: Object -&gt; Maybe String</span>
<span class="hljs-keyword">const</span> getStreetName = ...
</code></pre>
<p><a target="_blank" href="https://www.freecodecamp.org/news/the-principles-of-functional-programming/#set-5">Check answers</a>.</p>
<h2 id="heading-exercise-answers">Exercise Answers</h2>
<p>The answers I propose are not the only ones. You may come up with your own, even better solutions.</p>
<p>As long as your solution works, that's great.</p>
<h3 id="heading-set-1">Set 1</h3>
<p><a target="_blank" href="https://www.freecodecamp.org/news/the-principles-of-functional-programming/#exercises-set-1-">Go back to exercise</a>.</p>
<ol>
<li>Pure functions: a, d, e / Impure functions: b, c</li>
</ol>
<p>For <em>e</em>, the answer might not be easy to understand.</p>
<p>It was this function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> counter = <span class="hljs-function">(<span class="hljs-params">start, end</span>) =&gt;</span> {
  <span class="hljs-comment">// ...</span>

  <span class="hljs-comment">// e</span>
  <span class="hljs-function">() =&gt;</span> counter(start + <span class="hljs-number">1</span>, end);
};
</code></pre>
<p>So it's one function inside another.</p>
<p>We said that a pure function shouldn't rely on the outside, but here it accesses variables outside its scope, those on which it has a closure over (<code>counter</code>, <code>start</code> and <code>end</code>).</p>
<p>In a pure functional language, unlike JavaScript, <code>counter</code>, <code>start</code> and <code>end</code> would be immutable so <em>e</em> would be pure because, for the same input (in this case none), we would always get the same output.</p>
<p>However, values in JavaScript are mutable by default.</p>
<p>So if <code>start</code> was an object for whatever reason, it could be mutated outside of <code>counter</code> or inside <em>e</em> itself.</p>
<p>In this case, <em>e</em> would be considered impure.</p>
<p>But because that's not the case here, I class it as a pure function.</p>
<p>See this <a target="_blank" href="https://softwareengineering.stackexchange.com/questions/235175/are-closures-considered-impure-functional-style">thread</a> for more details.</p>
<p>2.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> people = [
  { <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Bill"</span>, <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Harold"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">54</span> },
  { <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Ana"</span>, <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Atkins"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">42</span> },
  { <span class="hljs-attr">firstname</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Doe"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">57</span> },
  { <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Davy"</span>, <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Johnson"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">34</span> },
];

<span class="hljs-keyword">const</span> uppercaseNames = <span class="hljs-function">(<span class="hljs-params">person</span>) =&gt;</span> ({
  <span class="hljs-attr">firstname</span>: person.firstname.toUpperCase(),
  <span class="hljs-attr">lastname</span>: person.lastname.toUpperCase(),
  <span class="hljs-attr">age</span>: person.age,
});

<span class="hljs-comment">// "sort" mutates the original array it's applied on.</span>
<span class="hljs-comment">// So I make a copy before ([...people]) to not mutate the original argument.</span>
<span class="hljs-keyword">const</span> sortByAge = <span class="hljs-function">(<span class="hljs-params">people</span>) =&gt;</span>
  [...people].sort(<span class="hljs-function">(<span class="hljs-params">person1, person2</span>) =&gt;</span> person1.age - person2.age);

<span class="hljs-keyword">const</span> parsePeople = <span class="hljs-function">(<span class="hljs-params">people</span>) =&gt;</span> sortByAge(people.map(uppercaseNames));

<span class="hljs-comment">// NOT SURE TO INCLUDE</span>
<span class="hljs-comment">// If you have already read the section on Composition (after this one), you may come up with</span>
<span class="hljs-comment">// a more readable version for "parsePeople":</span>
<span class="hljs-keyword">const</span> parsePeople = pipe(map(uppercaseNames), sortByAge);
<span class="hljs-comment">// or</span>
<span class="hljs-keyword">const</span> parsePeople = compose(sortByAge, map(uppercaseNames));

parsePeople(people);
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   {firstname: "DAVY", lastname: "JOHNSON", age: 34},</span>
<span class="hljs-comment">//   {firstname: "ANA", lastname: "ATKINS", age: 42},</span>
<span class="hljs-comment">//   {firstname: "BILL", lastname: "HAROLD", age: 54},</span>
<span class="hljs-comment">//   {firstname: "JOHN", lastname: "DOE", age: 57},</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<p>That's the version I came with, but any variation works from the moment it has no side-effects.</p>
<p>The function in the exercise indeed mutates the object passed as argument.</p>
<p>But you can verify that the original <code>people</code> array is unchanged in this correction.</p>
<h3 id="heading-set-2">Set 2</h3>
<p><a target="_blank" href="https://www.freecodecamp.org/news/the-principles-of-functional-programming/#exercises-set-2-">Go back to exercise</a>.</p>
<ol>
<li><p>```js
const input =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";</p>
</li>
</ol>
<p>// ...</p>
<p>// keepLetters :: [Character] -&gt; [Character] | []
const keepLetters = filter((char) =&gt;
  "abcdefghijklmnopqrstuvwxyz".includes(char)
);</p>
<p>// getLetters :: String -&gt; [Character]
const getLetters = pipe(
  lowercase,
  getChars,
  keepLetters,
  removeDuplicates,
  sort
);
// or
const getLetters = compose(
  sort,
  removeDuplicates,
  keepLetters,
  getChars,
  lowercase
);</p>
<p>getLetters(input);
// ["a", "b", "c", "d", "e", "f", "g", "h", "i", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "x"]</p>
<pre><code>
<span class="hljs-number">2.</span>

<span class="hljs-string">``</span><span class="hljs-string">`js
// getMedianAges :: [Key, [Person]] -&gt;  [Key, Object]
const getMedianAges = reduceOverVal((acc, person) =&gt; {
  const key = `</span>medianAge${person.sex}<span class="hljs-string">`;

  return !acc[key]
    ? { ...acc, [key]: person.age }
    : { ...acc, [key]: mean(acc[key], person.age) };
}, {});

// groupsMedianAges :: Object -&gt; Object
const groupsMedianAges = pipe(getEntries, map(getMedianAges), fromEntries);
// or
const groupsMedianAges = compose(fromEntries, map(getMedianAges), getEntries);</span>
</code></pre><p>3.</p>
<pre><code class="lang-js"><span class="hljs-comment">// reduce :: (b -&gt; a -&gt; b) -&gt; b -&gt; [a] -&gt; b</span>
</code></pre>
<p>4.</p>
<pre><code class="lang-js"><span class="hljs-comment">// curry :: ((a, b, ...) -&gt; c) -&gt; a -&gt; b -&gt;  ... -&gt; c</span>
</code></pre>
<h3 id="heading-set-3">Set 3</h3>
<p><a target="_blank" href="https://www.freecodecamp.org/news/the-principles-of-functional-programming/#exercises-set-3-">Go back to exercise</a>.</p>
<ol>
<li><p>```js
const uppercaseF = map((str) =&gt; str.toUpperCase())</p>
</li>
</ol>
<p>// Example:
const myFunctor = Just("string")</p>
<p>uppercaseF(myFunctor)
// Just("STRING")</p>
<pre><code>
<span class="hljs-number">2.</span>

<span class="hljs-string">``</span><span class="hljs-string">`js
const uppercaseF = map((str) =&gt; str.toUpperCase());

// Example:
const myFunctor = Just("string");

uppercaseF(myFunctor);
// Just("STRING")</span>
</code></pre><p>2.</p>
<pre><code class="lang-js"><span class="hljs-comment">// printUsername :: User -&gt; _</span>
<span class="hljs-keyword">const</span> printUsername = pipe(
  safeProp(<span class="hljs-string">"name"</span>),
  uppercaseF,
  maybe(<span class="hljs-string">"Username not found !"</span>, <span class="hljs-built_in">console</span>.log)
);

<span class="hljs-comment">// Example:</span>
printUsername({
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Yann Salmon"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">18</span>,
  <span class="hljs-attr">interests</span>: [<span class="hljs-string">"Programming"</span>, <span class="hljs-string">"Sport"</span>, <span class="hljs-string">"Reading"</span>, <span class="hljs-string">"Math"</span>],
  <span class="hljs-comment">// ...</span>
});
<span class="hljs-comment">// console: YANN SALMON</span>
</code></pre>
<h3 id="heading-set-4">Set 4</h3>
<p><a target="_blank" href="https://www.freecodecamp.org/news/the-principles-of-functional-programming/#exercises-set-4-">Go back to exercise</a>.</p>
<ol>
<li><p>```js
// getPartnerName :: User -&gt; Maybe String
const getPartnerName = pipe(safeProp("partner"), map(getName));</p>
</li>
</ol>
<p>// userName :: Maybe String
const userName = Maybe.of(getName(user));
// partnerName :: Maybe String
const partnerName = getPartnerName(user);</p>
<p>// couple :: Maybe String
const couple = Maybe.of(getCouplePresentation).ap(userName).ap(partnerName);
// Just("John Doe and Theresa Doe are partners.")</p>
<pre><code>
<span class="hljs-number">2.</span>

<span class="hljs-string">``</span><span class="hljs-string">`js
// ...

const couple = liftA2(getCouplePresentation, userName, partnerName);</span>
</code></pre><h3 id="heading-set-5">Set 5</h3>
<p><a target="_blank" href="https://www.freecodecamp.org/news/the-principles-of-functional-programming/#exercises-set-5-">Go back to exercise</a>.</p>
<ol>
<li><p>```js
// ...</p>
</li>
</ol>
<p>// getStreetName :: Object -&gt; Maybe String
const getStreetName = pipe(
  safeProp("address"),
  chain(safeProp("street")),
  chain(safeProp("name"))
);</p>
<p>getStreetName(restaurant);
// Just("Melrose Avenue")
```</p>
<h2 id="heading-going-further">Going further</h2>
<p>This post is mainly inspired by what I learned from these 3 amazing resources (in order of difficulty):</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/playlist?list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84">Fun Fun Function playlist</a> (video)</li>
<li><a target="_blank" href="https://github.com/getify/Functional-Light-JS">Functional-Light JavaScript</a> (book)</li>
<li><a target="_blank" href="https://mostly-adequate.gitbooks.io/mostly-adequate-guide/content/">Mostly adequate guide for Functional Programming</a> (book)</li>
</ul>
<p>Like me, you'll certainly find some concepts really hard to grasp at first.</p>
<p>But please keep going. Don't hesitate to rewind videos and reread paragraphs after a good night of sleep.</p>
<p>I ensure you that it will pay off.</p>
<p>There's also a great <a target="_blank" href="https://github.com/stoeffel/awesome-fp-js">Github repository</a> that gather resources about Functional Programming in JavaScript.</p>
<p>You'll find, among other things, nice libraries that provide functional helpers. My favorite at the time is <a target="_blank" href="https://ramdajs.com/">Ramda JS</a>. Others also provide monads like <a target="_blank" href="https://sanctuary.js.org/">Sanctuary</a>.</p>
<p>I certainly don't know everything about Functional Programming, so there are topics I didn't cover.</p>
<p>Those I'm aware of are:</p>
<ul>
<li>A technique called <strong>transducing</strong>. In short, it's a way of composing <code>map</code>, <code>filter</code> and <code>reduce</code> operations together. Check <a target="_blank" href="https://github.com/getify/Functional-Light-JS/blob/master/manuscript/apA.md/#appendix-a-transducing">this</a> and <a target="_blank" href="https://www.youtube.com/watch?v=6mTbuzafcII">that</a> to learn more.</li>
<li>Other common types of monads: Either, Map, List</li>
<li>Other algebraic structures like semi-groups and monoids</li>
<li><a target="_blank" href="https://www.learnrxjs.io/">Functional Reactive Programming</a></li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>That's it!</p>
<p>Before we finish, I want to warn you about potential mistakes.</p>
<p>I'm not an expert in Functional Programming, so please be critical of this article as you learn more about it. I'm always open to discussions and refinements.</p>
<p>In any case, I hope that I laid down what I consider to be the fundamentals necessary for you to be more productive in your day-to-day work, as well as giving you the tools and the interest to go further.</p>
<p>And with that, keep coding! ?</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ TypeScript Types Explained – A Mental Model to Help You Think in Types ]]>
                </title>
                <description>
                    <![CDATA[ By TK One day I came across this tweet from Lari Mazza: As a software engineer who learned Python, Ruby, JavaScript, and Clojure first, when I tried C++ it was a horror movie. I couldn't do much, and it was so counterproductive and frustrating. Mayb... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-mental-model-to-think-in-typescript-2/</link>
                <guid isPermaLink="false">66d852a75732345ee5fa9335</guid>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 21 Jul 2020 11:05:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/07/cover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By TK</p>
<p>One day I came across this <a target="_blank" href="https://twitter.com/larimaza/status/1275747670989176833">tweet</a> from Lari Mazza:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/typescript.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As a software engineer who learned Python, Ruby, JavaScript, and Clojure first, when I tried C++ it was a horror movie. I couldn't do much, and it was so counterproductive and frustrating. Maybe because I was doing everything wrong and I didn't understand types the right way.</p>
<p>But even though I had so many problems, I could implement a bunch of <a target="_blank" href="https://github.com/leandrotk/algorithms">algorithms and data structures</a>.</p>
<p>Now that I'm using more and more TypeScript in my day-to-day job and <a target="_blank" href="https://github.com/leandrotk/laziness">my side projects</a>, I feel I'm more prepared to confront types. Actually, not confront, but use them in my favor.</p>
<p>This post is my attempt to help developers think more in types and understand this mental model.</p>
<h2 id="heading-thinking-in-javascript-types">Thinking in JavaScript types</h2>
<p>If you're here, you've probably heard that TypeScript is a superset of JavaScript. If not, great, you just learned something new today. YAY!</p>
<p>TypeScript is a superset because any JavaScript code is valid in TypeScript, syntactically speaking. It may or may not compile depending on the TypeScript compiler configuration. But in terms of syntax, it works just fine. </p>
<p>This is why you can migrate JavaScript to TypeScript progressively by just replacing the <code>.js</code> extension with the <code>.ts</code>. Everything will be without type declarations (the <code>any</code> type), but that's another story.</p>
<p>Also, if you code in JavaScript - or any other programming language - you probably think in types:</p>
<ul>
<li>"Hm, it is a list of integers, so I'll need to filter only the even numbers and return a new list"</li>
<li>"This is an object, but I just need to get this string value from the property X"</li>
<li>"This function receives two parameters. Both A and B are integers and I want to sum them"</li>
</ul>
<p>Yeah, you get the idea. We think in types. But they are just in our heads. We constantly think about them because we need to know how to handle, parse, or modify data. We need to know which methods we are allowed to use in this object type.</p>
<p>To give a more concrete example, imagine you want to sum the price of all products. A product object looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> product = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>But now with a list of products:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> products = [
  {
    title: <span class="hljs-string">'Product 1'</span>,
    price: <span class="hljs-number">100.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 2'</span>,
    price: <span class="hljs-number">25.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 3'</span>,
    price: <span class="hljs-number">300.00</span>,
  }
];
</code></pre>
<p>Ok! Now we want a function to sum all the products prices.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAllPrices</span>(<span class="hljs-params">products</span>) </span>{
  <span class="hljs-keyword">return</span> products.reduce(<span class="hljs-function">(<span class="hljs-params">sum, product</span>) =&gt;</span> sum + product.price, <span class="hljs-number">0</span>);
};

sumAllPrices(products); <span class="hljs-comment">// 425</span>
</code></pre>
<p>Just receive the products as the argument and reduce all product prices. JavaScript works just fine. But while building this function you start to think about the data and how to handle it properly.</p>
<p>The first part: products as an argument. Here you just think: "well, we're receiving a list of some objects". Yeah, in our heads the products are a list. This is why we can think of using the <code>reduce</code> method. It is a method from the <code>Array</code> prototype.</p>
<p>Then we can think about the object in detail. We know that the product object has a <code>price</code> property. And this property is a number. This is why we can do <code>product.price</code> and sum with the accumulator.</p>
<p>Recapping:</p>
<ul>
<li><code>products</code> is a list of objects.</li>
<li>As a list, we can use the <code>reduce</code> method, as this method is a member of the <code>Array</code> prototype.</li>
<li>The <code>produce</code> object has some properties. One of them is the <code>price</code>, which is a number.</li>
<li>As a number property, we can use it to sum with the reduce accumulator.</li>
<li>We wanted to return a number, the sum of all products prices.</li>
</ul>
<p>We are always thinking of data types, we just need to add the type annotations to make it more explicit and ask the compiler for help. Our memory is limited and the compilers are here to help us, humans.</p>
<p>The type system will not only make our data more consistent, but it can also provide autocompletion for data types. It knows the types, so it can show the members for the data. We will take a look at this idea later. Here I just wanted to show that we think in types in our heads.</p>
<h2 id="heading-simples-types-amp-simple-uses">Simples Types &amp; Simple Uses</h2>
<p>So we are ready to use some strongly typed programming languages like TypeScript. We simply need to explicitly add type annotations to our data structures. It's simple, right? </p>
<p>But sometimes it's not that easy (usually it's not easy when you come from dynamically typed languages. You feel unproductive. It feels like a battle against types). The idea here is to make this learning curve smoother and more fun.</p>
<p>Here we will see many examples of how to use types in TypeScript. We'll start with easy and silly examples and progressively make it more complex while designing the mental model to think in types.</p>
<p>As in JavaScript, TypeScript also has basic data types like <code>number</code>, <code>string</code>, <code>boolean</code>, <code>null</code>, etc. You can find all the basic data types in the <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/basic-types.html">TypeScript Docs</a>.</p>
<p>With these units of data, we can make our programs more useful. To be more practical, let's get a simple example. A <code>sum</code> function.</p>
<p>How does it work in JavaScript?</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>Everything ok? Good.</p>
<p>Now let's use it:</p>
<pre><code class="lang-typescript">sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 3</span>
sum(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 4</span>
sum(<span class="hljs-number">0</span>, <span class="hljs-string">'string'</span>); <span class="hljs-comment">// '0string'   WTF!</span>
</code></pre>
<p>The first two calls are what we expect to happen in our system. But JavaScript is very flexible, it lets us provide any value to this function. </p>
<p>The last call is bizarre. We can call with a string, but it will return an unexpected result. It doesn't break in development, but it will result in strange behavior in runtime.</p>
<p>What do we want? We want to add some constraints to the function. It will only be able to receive numbers. That way, we narrow the possibility of having unexpected behaviors. And the function return type is also a number.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>Great! It was very simple. Let's call again.</p>
<pre><code class="lang-typescript">sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 3</span>
sum(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 4</span>
sum(<span class="hljs-number">0</span>, <span class="hljs-string">'string'</span>); <span class="hljs-comment">// Argument of type '"string"' is not assignable to parameter of type 'number'.</span>
</code></pre>
<p>As we type annotate our function, we provide information to the compiler to see if everything is correct. It will follow the constraints we added to the function.</p>
<p>So the first two calls are the same as in JavaScript. It will return the correct calculation. But in the last one we have an error in compile time. This is important. The error now happens in compile time and prevents us from shipping incorrect code to production. It says that the <code>string</code> type is not part of the set of values in the <code>number</code> type universe.</p>
<p>For basic types, we just need to add a colon followed by the type definition.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> isTypescript: <span class="hljs-built_in">boolean</span> = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> age: <span class="hljs-built_in">number</span> = <span class="hljs-number">24</span>;
<span class="hljs-keyword">const</span> username: <span class="hljs-built_in">string</span> = <span class="hljs-string">'tk'</span>;
</code></pre>
<p>Now let's increase the challenge. Remember the product object code we wrote in JavaScript? Let's implement it again, but now with the TypeScript mindset.</p>
<p>Just to remember what we are talking about:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> product = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>This is the product value. It has a <code>title</code> as <code>string</code> and the <code>price</code> as <code>number</code>. For now, this is what we need to know.</p>
<p>The object type would be something like this:</p>
<pre><code class="lang-typescript">{ title: <span class="hljs-built_in">string</span>, price: <span class="hljs-built_in">number</span> }
</code></pre>
<p>And we use this type to annotate our function:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> product: { title: <span class="hljs-built_in">string</span>, price: <span class="hljs-built_in">number</span> } = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>With this type, the compiler will know how to handle inconsistent data:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> wrongProduct: { title: <span class="hljs-built_in">string</span>, price: <span class="hljs-built_in">number</span> } = {
  title: <span class="hljs-number">100.00</span>, <span class="hljs-comment">// Type 'number' is not assignable to type 'string'.</span>
  price: <span class="hljs-string">'Some product'</span>, <span class="hljs-comment">// Type 'string' is not assignable to type 'number'.</span>
};
</code></pre>
<p>Here it breaks down into two different properties:</p>
<ul>
<li>The <code>title</code> is a <code>string</code> and should not receive a <code>number</code>.</li>
<li>The <code>price</code> is a <code>number</code> and should not receive a <code>string</code>.</li>
</ul>
<p>The compiler helps us to catch type errors like that.</p>
<p>We could improve this type annotation by using a concept called <code>Type Aliases</code>. It's a way to create a new name for a specific type.</p>
<p>In our case, the product type could be:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Product = {
  title: <span class="hljs-built_in">string</span>;
  price: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">const</span> product: Product = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>It's better to visualize the type, add semantics, and maybe reuse in our system.</p>
<p>Now that we have this product type, we can use it to type the products list. The syntax looks like this: <code>MyType[]</code>. In our case, <code>Product[]</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> products: Product[] = [
  {
    title: <span class="hljs-string">'Product 1'</span>,
    price: <span class="hljs-number">100.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 2'</span>,
    price: <span class="hljs-number">25.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 3'</span>,
    price: <span class="hljs-number">300.00</span>,
  }
];
</code></pre>
<p>Now the function <code>sumAllPrices</code>. It will receive the product and return a number, the sum of all product prices.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAllPrices</span>(<span class="hljs-params">products: Product[]</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> products.reduce(<span class="hljs-function">(<span class="hljs-params">sum, product</span>) =&gt;</span> sum + product.price, <span class="hljs-number">0</span>);
};
</code></pre>
<p>This is very interesting. As we typed the product, when we write <code>product.</code>, it will show the possible properties we can use. In the product type case, it will show the properties <code>price</code> and <code>title</code>.</p>
<pre><code class="lang-typescript">sumAllPrices(products); <span class="hljs-comment">// 425</span>
sumAllPrices([]); <span class="hljs-comment">// 0</span>
sumAllPrices([{ title: <span class="hljs-string">'Test'</span>, willFail: <span class="hljs-literal">true</span> }]); <span class="hljs-comment">// Type '{ title: string; willFail: true; }' is not assignable to type 'Product'.</span>
</code></pre>
<p>Passing the <code>products</code> will result in the value <code>425</code>. An empty list will result in the value <code>0</code>. And if we pass an object with a different structure - TypeScript has a structural type system and we will dig deep into this topic later - the compiler will throw a type error telling that the structure is not part of the <code>Product</code> type.</p>
<h2 id="heading-structural-typing">Structural Typing</h2>
<p>Structural typing is a type of type compatibility. It's a way to understand the compatibility between types based on its structure: features, members, properties. Some languages have type compatibility based on the names of the types, and it's called nominal typing.</p>
<p>For example, in Java, even if different types have the same structure, it will throw a compile error because we are using a different type to instantiate and define a new instance.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Person {
  <span class="hljs-built_in">String</span> name;
}

<span class="hljs-keyword">class</span> Client {
  <span class="hljs-built_in">String</span> name;
}

Client c = <span class="hljs-keyword">new</span> Person();  <span class="hljs-comment">// compiler throws an error</span>
Client c = <span class="hljs-keyword">new</span> Client();  <span class="hljs-comment">// OK!</span>
</code></pre>
<p>In nominal type systems, the relevant part of a type is the name, not the structure.</p>
<p>TypeScript, on another hand, verifies the structural compatibility to allow or not specific data. Its type system is based on structural typing.</p>
<p>The same code implementation that crashes in Java, would work in TypeScript.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Person {
  name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">class</span> Client {
  name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">const</span> c1: Client = <span class="hljs-keyword">new</span> Person(); <span class="hljs-comment">// OK!</span>
<span class="hljs-keyword">const</span> c2: Client = <span class="hljs-keyword">new</span> Client(); <span class="hljs-comment">// OK!</span>
</code></pre>
<p>We want to use the <code>Client</code> type, and it has the property <code>name</code>, to point to the <code>Person</code> type. It also has the property type. So TypeScript will understand that both types have the same shape.</p>
<p>But it is not only about classes, but it works for any other "object".</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> c3: Client = {
  name: <span class="hljs-string">'TK'</span>
};
</code></pre>
<p>This code compiles too because we have the same structure here. The TypeScript type system doesn't care about if it is a class, or an object literal if it has the same members, it will be flexible and compile.</p>
<p>But now we will add a third type: the <code>Customer</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Customer {
  name: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
};
</code></pre>
<p>It not only has the <code>name</code> property, but also the <code>age</code>. What would happen if we instantiate a <code>Client</code> instance in a constant of type <code>Customer</code>?</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> c4: Customer = <span class="hljs-keyword">new</span> Client();
</code></pre>
<p>The compiler will not accept that. We want to use the <code>Customer</code>, that has <code>name</code> and <code>age</code>. But we are instantiating the <code>Client</code> that has only the <code>name</code> property. So it doesn't have the same shape. It will cause an error:</p>
<pre><code class="lang-bash">Property <span class="hljs-string">'age'</span> is missing <span class="hljs-keyword">in</span> <span class="hljs-built_in">type</span> <span class="hljs-string">'Client'</span> but required <span class="hljs-keyword">in</span> <span class="hljs-built_in">type</span> <span class="hljs-string">'Customer'</span>.
</code></pre>
<p>The other way around would work because we want <code>Client</code>, and <code>Customer</code> has all the properties (<code>name</code>) from <code>Client</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> c5: Client = <span class="hljs-keyword">new</span> Customer();
</code></pre>
<p>It works fine!</p>
<p>We can go on for enums, object literals, and any other type, but the idea here is to understand that the structure of the type is the relevant part.</p>
<h2 id="heading-runtime-and-compile-time">Runtime and Compile time</h2>
<p>This is a much more complex topic in programming language theory, but I wanted to give some examples to distinguish runtime from compile time.</p>
<p>Basically, the runtime is the execution time of a program. Imagine your backend receiving data from a frontend form page, handling this data, and saving it. Or when your frontend is requesting data from a server to render a list of Pokemons products.</p>
<p>Compile time is basically when the compiler is executing operations in the source code to satisfy the programming language's requirements. It can include type checking as an operation, for example. </p>
<p>Compile time errors in TypeScript, for example, are very related to the code that we wrote before:</p>
<ul>
<li>When the type is missing property: <code>Property 'age' is missing in type 'Client' but required in type 'Customer'.</code></li>
<li>When the type doesn't match: <code>Type '{ title: string; willFail: true; }' is not assignable to type 'Product'.</code></li>
</ul>
<p>Let's see some examples to have a better understanding.</p>
<p>I want to write a function to get the index of a part of the passed programming language.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getIndexOf</span>(<span class="hljs-params">language, part</span>) </span>{
  <span class="hljs-keyword">return</span> language.indexOf(part);
}
</code></pre>
<p>It receives the <code>language</code> and the <code>part</code> that we will look for to get the index.</p>
<pre><code class="lang-typescript">getIndexOf(<span class="hljs-string">'Typescript'</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// 4</span>
getIndexOf(<span class="hljs-number">42</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// Uncaught TypeError: language.indexOf is not a function at getIndexOf</span>
</code></pre>
<p>When passing a string, it works fine. But passing a number, we got a runtime error <code>Uncaught TypeError</code>. Because a number doesn't have an <code>indexOf</code> function, so we can't really use it.</p>
<p>But if we give type information to the compiler, in compile time, it will throw an error before running the code.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getIndexOf</span>(<span class="hljs-params">language: <span class="hljs-built_in">string</span>, part: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> language.indexOf(part);
}
</code></pre>
<p>Now our program knows that it will need to receive two strings and return a number. The compiler can use this information to throw errors when we get a type error... before runtime.</p>
<pre><code class="lang-typescript">getIndexOf(<span class="hljs-string">'Typescript'</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// 4</span>
getIndexOf(<span class="hljs-number">42</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// Argument of type '42' is not assignable to parameter of type 'string'.</span>
</code></pre>
<p>Maybe, for small projects (or small functions like ours) we don't really see too much benefit. </p>
<p>In this case, we know that we need to pass a string, so we won't pass a number to the function. But when the codebase grows or you have many people adding code and more complexity, it's clear to me that a type system can help us a lot to get errors in compile time before shipping code to production.</p>
<p>At first, we need all the learning curve to understand types and all the mental models, but after a while, you'll be more used to type annotations and eventually become friends with the compiler. It would be a <em>helper</em>, not a <em>yeller</em>.</p>
<p>As we are learning about the basic difference between compile time and runtime, I think it's great to differentiate types from values.</p>
<p>All the examples I'll show here can be copied and run in the <a target="_blank" href="https://www.typescriptlang.org/play">TypeScript Playground</a> to understand the compiler and the result of the compilation process (aka the <em>"JavaScript"</em>).</p>
<p>In TypeScript, we have two different universes: the value and the type spaces. The type space is where types are defined and used to enable the compiler to do all the great magic. And the value space is the values in our programs like variables, constants, functions, value literals, and things that we have in runtime.</p>
<p>It's good to have an understanding of this concept because in TypeScript we can't use type checking in runtime. It has a very clear separation between type checking and the compilation process.</p>
<p>TypeScript has the process of type checking the source code types and sees if everything is correct and consistent. And then it can compile to JavaScript. </p>
<p>As these two parts are separate, we can't use type checking in runtime. Only in "compile time". If you try to use a type as a value, it will throw an error: <code>only refers to a type, but is being used as a value here</code>.</p>
<p>Let's see examples of this idea.</p>
<p>Imagine we want to write a function called <code>purchase</code> where we receive a payment method and based on this method, we want to do some action. We have a credit card and a debit card. Let's define them here:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> CreditCard = {
  <span class="hljs-built_in">number</span>: <span class="hljs-built_in">number</span>;
  cardholder: <span class="hljs-built_in">string</span>;
  expirationDate: <span class="hljs-built_in">Date</span>;
  secutiryCode: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> DebitCard = {
  <span class="hljs-built_in">number</span>: <span class="hljs-built_in">number</span>;
  cardholder: <span class="hljs-built_in">string</span>;
  expirationDate: <span class="hljs-built_in">Date</span>;
  secutiryCode: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> PaymentMethod = CreditCard | DebitCard;
</code></pre>
<p>These types are in the <em>Type space</em>, so it only works in compile time. After type checking this function, the compiler removes all the types.</p>
<p>If you add these types in the TypeScript Playground, the output will be only a strict definition <code>"use strict";</code>.</p>
<p>The idea here is to really understand that the types live in the <em>Type space</em> and will not be available in the runtime. So in our function, it won't be possible to do this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> purchase = <span class="hljs-function">(<span class="hljs-params">paymentMethod: PaymentMethod</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (paymentMethod <span class="hljs-keyword">instanceof</span> CreditCard) {
    <span class="hljs-comment">// purchase with credit card</span>
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// purchase with debit card</span>
  }
}
</code></pre>
<p>In the compiler it throws an error: <code>'CreditCard' only refers to a type, but is being used as a value here.</code>.</p>
<p>The compiler knows the difference between the two spaces and that the type <code>CreditCard</code> lives in the <em>Type space</em>.</p>
<p>The playground is a very cool tool to see the output of your TypeScript code. If you create a new credit card object like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> creditCard: CreditCard = {
  <span class="hljs-built_in">number</span>: <span class="hljs-number">2093</span>,
  cardholder: <span class="hljs-string">'TK'</span>,
  expirationDate: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(),
  secutiryCode: <span class="hljs-number">101</span>
};
</code></pre>
<p>The compiler will type check it and do all the magic and then it transpiles the TypeScript code to JavaScript. And we have this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> creditCard = {
    <span class="hljs-built_in">number</span>: <span class="hljs-number">2093</span>,
    cardholder: <span class="hljs-string">'TK'</span>,
    expirationDate: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(,
    secutiryCode: <span class="hljs-number">101</span>
};
</code></pre>
<p>The same object, but now only with the value and without the type.</p>
<h2 id="heading-constraints-amp-type-narrowing">Constraints &amp; Type Narrowing</h2>
<p>When we restrict what we can do, it’s easier to understand what we can do.</p>
<p>We use types as constraints to limit the bugs in your program. To understand this concept, I'm stealing an example from Lauren Tan's talk about Type Systems.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> half = <span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x / <span class="hljs-number">2</span>;
</code></pre>
<p>How many ways does this function can fail? Imagine a number of possible inputs:</p>
<pre><code class="lang-typescript">[
  <span class="hljs-literal">null</span>,
  <span class="hljs-literal">undefined</span>,
  <span class="hljs-number">0</span>,
  <span class="hljs-string">'0'</span>,
  <span class="hljs-string">'TK'</span>,
  { username: <span class="hljs-string">'tk'</span> },
  [<span class="hljs-number">42</span>, <span class="hljs-number">3.14</span>],
  <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b,
]
</code></pre>
<p>And what are the results for input:</p>
<pre><code class="lang-typescript">half(<span class="hljs-literal">null</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-literal">undefined</span>); <span class="hljs-comment">// NaN</span>
half(<span class="hljs-number">0</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-string">'0'</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-string">'TK'</span>); <span class="hljs-comment">// NaN</span>
half({ username: <span class="hljs-string">'tk'</span> }); <span class="hljs-comment">// NaN</span>
half([<span class="hljs-number">42</span>, <span class="hljs-number">3.14</span>]); <span class="hljs-comment">// NaN</span>
half(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b); <span class="hljs-comment">// NaN</span>
</code></pre>
<p>We have different and unexpected results here. Here it's clear that we want a number as the <code>half</code> function, do the calculation, and great, it's done! But sometimes we don't control the input or the codebase is big, or new/unfamiliar, and we're able to make these little mistakes.</p>
<p>The idea of adding constraints to our code is to narrow the possibilities of a range of types. In this case, we want to limit the input type to a <code>number</code> type. It's the only type that we care about to do the half calculation. With type narrowing, we again give type information to the compiler.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> half = <span class="hljs-function">(<span class="hljs-params">x: <span class="hljs-built_in">number</span></span>) =&gt;</span> x / <span class="hljs-number">2</span>;
</code></pre>
<p>And with this new information, if we call the function with the test cases again, we have different results:</p>
<pre><code class="lang-typescript">half(<span class="hljs-literal">null</span>); <span class="hljs-comment">// Argument of type 'null' is not assignable to parameter of type 'number'.</span>
half(<span class="hljs-literal">undefined</span>); <span class="hljs-comment">// Argument of type 'undefined' is not assignable to parameter of type 'number'.(</span>
half(<span class="hljs-number">0</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-string">'0'</span>); <span class="hljs-comment">// Argument of type '"0"' is not assignable to parameter of type 'number'.</span>
half(<span class="hljs-string">'TK'</span>); <span class="hljs-comment">// Argument of type '"TK"' is not assignable to parameter of type 'number'.</span>
half({ username: <span class="hljs-string">'tk'</span> }); <span class="hljs-comment">// Argument of type '{ username: string; }' is not assignable to parameter of type 'number'.</span>
half([<span class="hljs-number">42</span>, <span class="hljs-number">3.14</span>]); <span class="hljs-comment">// Argument of type 'number[]' is not assignable to parameter of type 'number'.</span>
half(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b); <span class="hljs-comment">// Argument of type '(a: any, b: any) =&gt; any' is not assignable to parameter of type 'number'.</span>
</code></pre>
<p>Basically the compiler will tell us that only the number type, in this case, the <code>0</code> value, is a valid input, it will compile, and allow to run the code. We narrow the input type and allow only the value we really want for this function.</p>
<p>But are other ways to narrow the types in TypeScript. Imagine we have a function that receives a parameter that can be either a string or a number.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> StringOrNumber = <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stringOrNumber</span>(<span class="hljs-params">value: StringOrNumber</span>) </span>{}
</code></pre>
<p>In the function body, the compiler won't know which methods or properties we can use for this type. Is it a string or number? We only know about the value in runtime. But we can narrow the type using the <code>typeof</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stringOrNumber</span>(<span class="hljs-params">value: StringOrNumber</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> value === <span class="hljs-string">'string'</span>) {
    <span class="hljs-comment">// value.</span>
        <span class="hljs-comment">// your ide will show you the possible methods from the string type</span>
        <span class="hljs-comment">// (parameter) value: string</span>
    value
  }

  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> value === <span class="hljs-string">'number'</span>) {
    <span class="hljs-comment">// value.</span>
        <span class="hljs-comment">// your ide will show you the possible methods from the number type</span>
        <span class="hljs-comment">// (parameter) value: number</span>
    value
  }
}
</code></pre>
<p>With an <code>if</code> statement and the <code>typeof</code>, we can give more information to the compiler. Now it will know the specific type for each <code>if</code> body.</p>
<p>The IDE knows what to show for the specific type. In runtime, when the value is a string, it will go to the first <code>if</code> statement, and the compiler will infer that the type is a string: <code>(parameter) value: string</code>.</p>
<p>When the value is a number, it will go to the second <code>if</code> statement and the compiler will infer that a type is a number: <code>(parameter) value: number</code>.</p>
<p>The <code>if</code> statement can be a helper to the compiler.</p>
<p>Another example is when we have an optional property in an object, but in a function, we need to return a value based on this optional value.</p>
<p>Imagine we have this type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> User = {
  name: <span class="hljs-built_in">string</span>;
  address: {
    street: <span class="hljs-built_in">string</span>;
    complement?: <span class="hljs-built_in">string</span>;
  }
};
</code></pre>
<p>It's a simple <code>User</code> type. Let's focus on the <code>complement</code> property. It's optional (take a closer look at the <code>?</code> symbol), which means that it can be a <code>string</code> or <code>undefined</code>.</p>
<p>Now we want to build a function to receive the user and get the length of the address complement. What about this?</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getComplementLength</span>(<span class="hljs-params">user: User</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> user.address.complement.length;
    <span class="hljs-comment">// (property) complement?: string | undefined</span>
  <span class="hljs-comment">// Object is possibly 'undefined'.</span>
}
</code></pre>
<p>As we see earlier, the <code>complement</code> can be a <code>string</code> or <code>undefined</code>. <code>undefined</code> doesn't really have a property called <code>length</code>:</p>
<pre><code class="lang-typescript">Uncaught <span class="hljs-built_in">TypeError</span>: Cannot read property <span class="hljs-string">'length'</span> <span class="hljs-keyword">of</span> <span class="hljs-literal">undefined</span>
</code></pre>
<p>We could make something like:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getComplementLength</span>(<span class="hljs-params">user: User</span>) </span>{
  <span class="hljs-keyword">return</span> user.address.complement?.length;
}
</code></pre>
<p>If the <code>complement</code> has a string value, we can call <code>length</code>, otherwise, it will return <code>undefined</code>. </p>
<p>So this function has two possible return types: <code>number | undefined</code>. But we want to ensure that we only return <code>number</code>. So we use a <code>if</code> or a ternary condition to narrow the type. It will only call <code>.length</code> when it has real value (or when it is not <code>undefined</code>).</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getComplementLength</span>(<span class="hljs-params">user: User</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> user.address.complement
    ? user.address.complement.length
    : <span class="hljs-number">0</span>;
}
</code></pre>
<p>If it is <code>undefined</code>, we return the minimum length: <code>0</code>. Now we can use the function with the right type design with and without the complement. Without compile and runtime errors.</p>
<pre><code class="lang-typescript">getComplementLength({
  name: <span class="hljs-string">'TK'</span>,
  address: {
    street: <span class="hljs-string">'Shinjuku Avenue'</span>
  }
}); <span class="hljs-comment">// 0</span>

getComplementLength({
  name: <span class="hljs-string">'TK'</span>,
  address: {
    street: <span class="hljs-string">'Shinjuku Avenue'</span>,
    complement: <span class="hljs-string">'A complement'</span>
  }
}); <span class="hljs-comment">// 12</span>
</code></pre>
<p>We'll get <code>0</code> from the first function call and <code>12</code> from the second call.</p>
<p>With this <code>if</code> concept, we can also use other helpers to do the same thing. We could use the <code>in</code> operator to verify a property from an object, a <code>Array.isArray</code> to verify an array, or the <code>instanceof</code> for any other class type.</p>
<p>We could also use more advanced concepts like assertion function or type guards, but I'll leave these concepts to future posts.</p>
<p>One thing that I want to dig deep in this <em>Constraints</em> topic is immutability.</p>
<p>In JavaScript and TypeScript, we have the idea of mutable objects. If you define value in a variable, we can reassign it with another value later.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> email = <span class="hljs-string">'harry.potter@mail.com'</span>;
email <span class="hljs-comment">// 'harry.potter@mail.com'</span>
email = <span class="hljs-string">'hermione.granger@mail.com'</span>;
email <span class="hljs-comment">// 'hermione.granger@mail.com'</span>
</code></pre>
<p>Now imagine you have a list of numbers. And you want to use a function to sum all of its numbers. The function looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumNumbers</span>(<span class="hljs-params">numbers: <span class="hljs-built_in">number</span>[]</span>) </span>{
  <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">let</span> num = numbers.pop();

  <span class="hljs-keyword">while</span> (num !== <span class="hljs-literal">undefined</span>) {
    sum += num;
    num = numbers.pop();
  }

  <span class="hljs-keyword">return</span> sum;
}
</code></pre>
<p>You call the function passing your list and get the result. It works just fine.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
sumNumbers(list); <span class="hljs-comment">// 10</span>
</code></pre>
<p>But what happened to your list? Did the function mutate it entirely?</p>
<pre><code class="lang-typescript">list; <span class="hljs-comment">// []</span>
</code></pre>
<p>If we use the list, it's empty now. The <code>pop</code> in the <code>sumNumbers</code> function is a "mutate" function. It gets the references and removes the item from them. It's not a copy, it's the real reference.</p>
<p>In runtime, we can use other functions or ways to do the same thing: using reduce, do a for loop without the need to <code>pop</code> items from the array.</p>
<p>But using TypeScript, we can provide immutability in compile time. If you are not using types, it's possible to use a type assertion <code>as const</code>. Imagine this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
};

author.books.push({
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">10.00</span>
});
</code></pre>
<p>Just an author object and then we add a new book to this author. The <code>push</code> method updates the book's array reference. It's a "mutate" method. Let's see if you use the const assertion <code>as const</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
} <span class="hljs-keyword">as</span> <span class="hljs-keyword">const</span>;

author.books.push({
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">10.00</span>
});
<span class="hljs-comment">// Property 'push' does not exist on type</span>
<span class="hljs-comment">// 'readonly [{ readonly title: "Leonardo Da Vinci"; readonly price: 50; }]'</span>
</code></pre>
<p>The compiler won't compile. It gets an error on the author's object. It's is now readonly, and as a readonly object, it has no method called <code>push</code> (or any "mutate" method). </p>
<p>We added a constraint to the author's object. Before it was a specific type (with all the "mutate" methods), and now we narrowed the type to be almost the same, but without the "mutate" methods. Type narrowing.</p>
<p>To continue, let's add types to this object. The <code>book</code> and the <code>author</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Book = {
  title: <span class="hljs-built_in">string</span>;
  price: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> Author = {
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: Book[];
};
</code></pre>
<p>Add the type to the author object:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author: Author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
};
</code></pre>
<p>Add the type to a new book object:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> book: Book = {
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">30</span>
};
</code></pre>
<p>And now we can add the new book to the author:</p>
<pre><code class="lang-typescript">author.name = <span class="hljs-string">'TK'</span>;
author.books.push(book);
</code></pre>
<p>It works just fine!</p>
<p>I want to show another way to add immutability in compile time. TypeScript has a utility type called <code>Readonly</code>.</p>
<p>You can add the <code>readonly</code> for each property in an object. Something like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Book = {
  <span class="hljs-keyword">readonly</span> title: <span class="hljs-built_in">string</span>;
  <span class="hljs-keyword">readonly</span> price: <span class="hljs-built_in">number</span>;
};
</code></pre>
<p>But it can be very repetitive. So we can use the <code>Readonly</code> utility to add the <code>readonly</code> to all properties of an object:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Book = Readonly&lt;{
  title: <span class="hljs-built_in">string</span>;
  price: <span class="hljs-built_in">number</span>;
}&gt;;
</code></pre>
<p>One thing to keep in mind is that it doesn't add the readonly for nested properties. For example, if we add the <code>Readonly</code> to the <code>Author</code> type, it won't add the <code>readonly</code> to the <code>Book</code> type too.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Author = Readonly&lt;{
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: Book[];
}&gt;;
</code></pre>
<p>All the properties from the author can't be reassigned, but you can mutate the <code>books</code> list here (<code>push</code>, <code>pop</code>, ...) because the <code>Book[]</code> is not readonly. Let's see it.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author: Author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
};

<span class="hljs-keyword">const</span> book: Book = {
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">30</span>
};

author.books.push(book);
author.books;
<span class="hljs-comment">/* =&gt;
 *
 * [
 *   {
 *     title: 'Leonardo Da Vinci',
 *     price: 50.00,
 *   },
 *   {
 *    title: 'Steve Jobs',
 *    price: 30
 *   }
 * ]
 *
 */</span>
</code></pre>
<p>The <code>push</code> will work just fine.</p>
<p>So, how do we enforce a readonly to the <code>books</code>? We need to make sure that the array is a readonly type. We can use the <code>Readonly</code>, or use another utility from TypeScript called <code>ReadonlyArray</code>. Let's see the two ways to do it.</p>
<p>With <code>Readonly</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Author = Readonly&lt;{
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: Readonly&lt;Book[]&gt;;
}&gt;;
</code></pre>
<p>With <code>ReadonlyArray</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Author = Readonly&lt;{
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: ReadonlyArray&lt;Book&gt;;
}&gt;;
</code></pre>
<p>For me, both work great! But in my opinion, <code>ReadonlyArray</code> is more semantic and I also feel it is less verbose (not that the <code>Readonly</code> with an array is).</p>
<p>What happened if we try to mutate the author object now?</p>
<pre><code class="lang-typescript">author.name = <span class="hljs-string">'TK'</span>; <span class="hljs-comment">// Cannot assign to 'name' because it is a read-only property.</span>
author.books.push(book); <span class="hljs-comment">// Property 'push' does not exist on type 'readonly [{ readonly title: "Leonardo Da Vinci"; readonly price: 50; }]'.</span>
</code></pre>
<p>Great! Now we can catch mutable operations in compile time. This is a way to use the concept of adding constraints to our types to make sure they only do what is really needed.</p>
<h2 id="heading-semantics-amp-readability">Semantics &amp; Readability</h2>
<p>At first, I felt that TypeScript could be very verbose because of the types and make the code much more complex than it should be. And it actually can. Strive for simplicity is the goal and it is difficult at the same time.</p>
<p>This idea is very related to clean code and how we can write code to be human-readable and maintainable. TypeScript is no different. Most of the cases, we don't need super complex types. Let the simple types do the work.</p>
<p>Another thing that I find very useful is semantic of types.</p>
<p>Imagine you need to add a string to the <code>sessionStorage</code> to save it in the browser. Your function looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saveMyString</span>(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">any</span> </span>{
  sessionStorage.myString = value;
}
</code></pre>
<p>You add a type annotation to the string input and as you don't know about the returning type, you probably add a <code>any</code> type.</p>
<p>But what's the real meaning behind this returning type? Is it returning anything?</p>
<p>It just saves the string to the <code>sessionStorage</code>. It doesn't return anything. The <code>void</code> type was what you're looking for. As TypeScript docs says: <code>the absence of having any type at all</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saveMyString</span>(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">void</span> </span>{
  sessionStorage.myString = value;
}
</code></pre>
<p>Great, the meaning of the type is correct now. The correctness is very important in a type system. It's a way to model our data, but also help maintain systems for future developers. Even if the developer is ... you!</p>
<p>Before we were talking about verbose code. And we can improve a lot of our code by using TypeScript type inference.</p>
<p>For some code, we don't need to explicitly add type annotation. The TypeScript compiler will understand and infer it implicitly. For example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> num: <span class="hljs-built_in">number</span> = <span class="hljs-number">1</span>;
</code></pre>
<p>This code is redundant. We can just let the compiler infers it like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> num = <span class="hljs-number">1</span>;
</code></pre>
<p>In our example earlier, we add the annotation <code>void</code> to the <code>saveMyString</code> function. But as the function doesn't return any value, the compiler will infer that the returning type is <code>void</code> implicitly.</p>
<p>When I learned this, I thought with myself. But one of the biggest advantages of using TypeScript (or any other type system / static type language) is types as documentation. If we let the compiler infer most of the types, we won't have the documentation we want.</p>
<p>But if you hover over the TypeScript code in your editor (at least VS Code works like that), you can see the type information and relevant documentation.</p>
<p>Let's see other examples of redundant code and make the code less verbose and let the compiler works for us.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>We don't need the returning type <code>number</code>, because the compiler knows that a <code>number</code> + another <code>number</code> is equal to a <code>number</code> type, and it is the returning type. It can be:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>Implicit code, but with documentation, and the compiler does the work.</p>
<p>Type inference works for methods too:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">squareAll</span>(<span class="hljs-params">numbers: <span class="hljs-built_in">number</span>[]</span>): <span class="hljs-title">number</span>[] </span>{
  <span class="hljs-keyword">return</span> numbers.map(<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> <span class="hljs-built_in">number</span> * <span class="hljs-built_in">number</span>);
};
</code></pre>
<p>This function gets a list of numbers and makes every number a squared value. The returning type is <code>number[]</code>, even though the result of a map is always a list, and as we have a list of numbers, it will always be a list of numbers. So we let the compiler infers this too:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">squareAll</span>(<span class="hljs-params">numbers: <span class="hljs-built_in">number</span>[]</span>) </span>{
  <span class="hljs-keyword">return</span> numbers.map(<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> <span class="hljs-built_in">number</span> * <span class="hljs-built_in">number</span>);
};
</code></pre>
<p>This works the same way for objects too.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> person: { name: <span class="hljs-built_in">string</span>, age: <span class="hljs-built_in">number</span> } = {
  name: <span class="hljs-string">'TK'</span>,
  age: <span class="hljs-number">24</span>
};
</code></pre>
<p>A person object with a string name and a number age. But as we are assigning these values, the compiler can infer these types.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> person = {
  name: <span class="hljs-string">'TK'</span>,
  age: <span class="hljs-number">24</span>
};
</code></pre>
<p>If you hover the <code>person</code>, you get this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> person: {
  name: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
}
</code></pre>
<p>The types are documented here.</p>
<p>Another benefit of type inference is that we can easily refactor our code. It's a simple example, but good to illustrate the refactoring process. Let's get the <code>sum</code> function again.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>Instead of returning the sum number, we want to return <code>"Sum: {a + b}"</code>. So for <code>a = 1</code> and <code>b = 2</code>, we have the resulting string as <code>"Sum: 3"</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">string</span> </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Sum: <span class="hljs-subst">${a + b}</span>`</span>;
};

sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// Sum: 3</span>
</code></pre>
<p>Great! But now letting the compiler infers this.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// function sum(a: number, b: number): number</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
};

<span class="hljs-comment">// function sum(a: number, b: number): string</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Sum: <span class="hljs-subst">${a + b}</span>`</span>;
};
</code></pre>
<p>We just need to modify the returning value and the type inference will work. No need to think about the returning type. This is a small example, but for more complex functions, it would work too.</p>
<p>Back to the readability part, we can use <code>Enum</code>. A utility that defines a set of named constants. It's a way to give more meaning to the data in your application.</p>
<p>In your node app or a frontend app, you possibly do some fetching to request data. You commonly use a fetch object to perform a request and sometimes you need to pass the accept headers.</p>
<pre><code class="lang-typescript">fetch(<span class="hljs-string">'/pokemons'</span>, {
  headers: {
    Accept: <span class="hljs-string">'application/json'</span>
  }
});

fetch(<span class="hljs-string">'/harry-potter/spells'</span>, {
  headers: {
    Accept: <span class="hljs-string">'application/json'</span>
  }
});
</code></pre>
<p>It's good, but we can also use an enum to separate this accept string in a constant and reuse.</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> MediaTypes {
  <span class="hljs-built_in">JSON</span> = <span class="hljs-string">'application/json'</span>
}

fetch(<span class="hljs-string">'/pokemons'</span>, {
  headers: {
    Accept: MediaTypes.JSON
  }
});

fetch(<span class="hljs-string">'/harry-potter/spells'</span>, {
  headers: {
    Accept: MediaTypes.JSON
  }
});
</code></pre>
<p>And we are able to add more data related to the <code>MediaTypes</code> like <code>PDF</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> MediaTypes {
  <span class="hljs-built_in">JSON</span> = <span class="hljs-string">'application/json'</span>,
  PDF = <span class="hljs-string">'application/pdf'</span>
}
</code></pre>
<p>With <code>Enum</code>, we can encapsulate data into a meaningful block of code.</p>
<p>Recently, I was implementing a "state" React component. It's basically a component that renders an empty state or an error state based on the request response.</p>
<p>The UI for the empty and the error states were very similar. Only the title and the description text and the image icon were different. So I thought: "I have two ways in my mind to implement this: do the logic outside the component and pass all the information needed or pass a 'state type' and let the component render the correct icon and messages."</p>
<p>So I built an enum:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-built_in">enum</span> StateTypes {
  Empty = <span class="hljs-string">'Empty'</span>,
  <span class="hljs-built_in">Error</span> = <span class="hljs-string">'Error'</span>
};
</code></pre>
<p>And I could just pass this data to the component as the <code>type</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> ComponentState, { StateTypes } <span class="hljs-keyword">from</span> <span class="hljs-string">'./ComponentState'</span>;

&lt;ComponentState <span class="hljs-keyword">type</span>={StateTypes.Empty} /&gt;
&lt;ComponentState <span class="hljs-keyword">type</span>={StateTypes.Error} /&gt;
</code></pre>
<p>In the component, it had a state object with all the information related to the <code>title</code>, <code>description</code>, and <code>icon</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> stateInfo = {
  Empty: {
    title: messages.emptyTitle,
    description: messages.emptyDescription,
    icon: EmptyIcon,
  },
  <span class="hljs-built_in">Error</span>: {
    title: messages.errorTitle,
    description: messages.errorDescription,
    icon: ErrorIcon,
  },
};
</code></pre>
<p>So I could just receive the type based on the enum and use this <code>stateInfo</code> object with the <code>State</code> component from our design system:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> ComponentState = <span class="hljs-function">(<span class="hljs-params">{ <span class="hljs-keyword">type</span> }</span>) =&gt;</span> (
  &lt;State
    title={stateInfo[<span class="hljs-keyword">type</span>].title}
    subtitle={stateInfo[<span class="hljs-keyword">type</span>].subtitle}
    icon={stateInfo[<span class="hljs-keyword">type</span>].icon}
  /&gt;
);
</code></pre>
<p>This is a way to use an enum to encapsulate important data into a meaningful block of code in your application.</p>
<p>Another cool feature from TypeScript is optional properties. When we have properties from an object that can be a real value or undefined, we use an optional property to be explicitly that the property can be or not be there. The syntax for this is a simple <code>?</code> operator in the object property. Imagine this function:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c;
}
</code></pre>
<p>But now the <code>c</code> value is optional:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c?: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c;
}
</code></pre>
<p>We add the <code>?</code> after <code>c</code>. But now we have a compiler error saying:</p>
<pre><code class="lang-typescript">(parameter) c: <span class="hljs-built_in">number</span> | <span class="hljs-literal">undefined</span>
<span class="hljs-built_in">Object</span> is possibly <span class="hljs-string">'undefined'</span>.
</code></pre>
<p>We can't sum an <code>undefined</code> value (well, actually in JavaScript we can, but we receive a <code>NaN</code> value).</p>
<p>We need to ensure that the <code>c</code> exists. Type narrowing!</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c?: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">if</span> (c) {
    <span class="hljs-keyword">return</span> a + b + c;
  }

  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>If the <code>c</code> exists, it will be a <code>number</code> and we can sum all. If not, sum only the <code>a</code> and <code>b</code> values.</p>
<p>An interesting part of this optional property is that it is a <code>undefined</code> not <code>null</code>. This is why we do this, we get a compile error:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> <span class="hljs-built_in">number</span> = <span class="hljs-literal">null</span>;
sumAll(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-built_in">number</span>);
<span class="hljs-comment">// Argument of type 'null' is not assignable to parameter of type 'number | undefined'.</span>
</code></pre>
<p>As the <code>?</code> operator doesn't handle the <code>null</code> value, choose to use the <code>undefined</code> type in your application and so you can still use the optional property and make the types consistent. We can use it like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> value: <span class="hljs-built_in">number</span> | <span class="hljs-literal">undefined</span>;
sumAll(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, value); <span class="hljs-comment">// 3</span>
</code></pre>
<p>If you add a default value to the parameter, you won't need the <code>?</code> operator. Actually, the compiler will say that the <code>Parameter cannot have question mark and initializer</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c: <span class="hljs-built_in">number</span> = 3</span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c;
}
</code></pre>
<p>Optional properties not only works on variables and parameters, but also in objects.</p>
<p>An API response is a good example of type definition and optional property together. In API responses, data can be optional. Sometimes the API sends, sometimes it has no value.</p>
<p>How we model our types is really important for an application. If an optional property is defined as a required type, we can make our application breaks in runtime. But if we design the types correctly, we have the possible errors in compile time.</p>
<p>Imagine we are fetching a user data and this is the way we modeled the response type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> UserResponse = {
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  username: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
  isActive: <span class="hljs-built_in">boolean</span>;
};
</code></pre>
<p>But in reality, the email is optional for the user. The API endpoint could return or not. But the <code>UserResponse</code> type we built treat it as a required property.</p>
<p>After fetching the user data, we want to see if the user email matches with a specific domain.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">matchDomain</span>(<span class="hljs-params">email: <span class="hljs-built_in">string</span></span>) </span>{
  <span class="hljs-keyword">return</span> email.endsWith(domain);
}
</code></pre>
<p>As the <code>email</code> property is required in the <code>UserResponse</code> type, the <code>email</code> parameter will also be required in the <code>matchDomain</code> function.</p>
<p>This is the runtime we can get if the <code>email</code> is <code>undefined</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Uncaught TypeError: Cannot read property 'endsWith' of undefined</span>
</code></pre>
<p>But what would happen if we modeled the <code>UserResponse</code> correctly?</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> UserResponse = {
  name: <span class="hljs-built_in">string</span>;
  email?: <span class="hljs-built_in">string</span>;
  username: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
  isActive: <span class="hljs-built_in">boolean</span>;
};
</code></pre>
<p>Now the <code>email</code> is possibly <code>undefined</code> and it is explicit.</p>
<p>But if we still keep the function <code>matchDomain</code> the same way, we get a compile error:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Argument of type 'undefined' is not assignable to parameter of type 'string'.</span>
</code></pre>
<p>And this is great! Now we can fix the <code>email</code> parameter in this function using the <code>?</code> operator:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">matchDomain</span>(<span class="hljs-params">email?: <span class="hljs-built_in">string</span></span>) </span>{
  <span class="hljs-keyword">return</span> email.endsWith(<span class="hljs-string">'email.com'</span>);
}
</code></pre>
<p>But now we get a compile error when running <code>email.endsWith</code>, because it could be <code>undefined</code> too:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// (parameter) email: string | undefined</span>
<span class="hljs-comment">// Object is possibly 'undefined'.</span>
</code></pre>
<p>Type narrowing! We use an if block to return a <code>false</code> when the <code>email</code> is <code>undefined</code>. And run <code>endsWith</code> method only if the <code>email</code> is really a string:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">matchDomain</span>(<span class="hljs-params">email?: <span class="hljs-built_in">string</span></span>) </span>{
  <span class="hljs-keyword">if</span> (!email) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  <span class="hljs-keyword">return</span> email.endsWith(<span class="hljs-string">'email.com'</span>);
}
</code></pre>
<p>It's pretty nice when we can get runtime errors in compile time. Better to code than debugging after we ship in production, isn't it?</p>
<h2 id="heading-type-composition">Type composition</h2>
<p>Type composition is very useful when trying to reuse existing types for new places of the codebase. We don't need to rewrite new types, we can create a new type by composing existing ones.</p>
<p>One example of composition I always have to handle using Redux or the <code>useReducer</code> hook from React is the idea of "reducers". A reducer can always receive a number of different actions.</p>
<p>In this context, actions are objects with at least a <code>type</code> property. It looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> ActionTypes {
  FETCH = <span class="hljs-string">'FETCH'</span>
}

<span class="hljs-keyword">type</span> FetchAction = {
  <span class="hljs-keyword">type</span>: <span class="hljs-keyword">typeof</span> ActionTypes.FETCH;
};

<span class="hljs-keyword">const</span> fetchAction: FetchAction = {
  <span class="hljs-keyword">type</span>: ActionTypes.FETCH
};
</code></pre>
<p>A <code>fetchAction</code> has a type <code>FetchAction</code> that has a property type that is a typeof <code>FETCH</code>.</p>
<p>But a reducer can receive other actions too. For example a submit action:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> ActionTypes {
  FETCH = <span class="hljs-string">'FETCH'</span>,
  SUBMIT = <span class="hljs-string">'SUBMIT'</span>
}

<span class="hljs-keyword">type</span> SubmitAction = {
  <span class="hljs-keyword">type</span>: <span class="hljs-keyword">typeof</span> ActionTypes.SUBMIT;
};

<span class="hljs-keyword">const</span> submitAction: SubmitAction = {
  <span class="hljs-keyword">type</span>: ActionTypes.SUBMIT
};
</code></pre>
<p>For a specific container, we can compose all these actions into just one type and use it for the reducer parameter type.</p>
<p>It would look like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Actions = FetchAction | SubmitAction;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state, action: Actions</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> ActionTypes.FETCH:
    <span class="hljs-comment">// fetching action</span>
    <span class="hljs-keyword">case</span> ActionTypes.SUBMIT:
    <span class="hljs-comment">// submiting action</span>
  }
}
</code></pre>
<p>All the possible actions are the <code>Actions</code> type. And we use a union type to "join" all action types. The action in the reducer can have the <code>FetchAction</code> or the <code>SubmitAction</code>.</p>
<p>As a Potterhead, I couldn't miss a Harry Potter example. I want to build a simple function to choose a Hogwarts House based on the person trait. Let's start with the houses first.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> House = {
  name: <span class="hljs-built_in">string</span>;
  traits: <span class="hljs-built_in">string</span>[];
}

<span class="hljs-keyword">const</span> gryffindor: House = {
  name: <span class="hljs-string">'Gryffindor'</span>,
  traits: [<span class="hljs-string">'courage'</span>, <span class="hljs-string">'bravery'</span>]
};

<span class="hljs-keyword">const</span> slytherin: House = {
  name: <span class="hljs-string">'Slytherin'</span>,
  traits: [<span class="hljs-string">'ambition'</span>, <span class="hljs-string">'leadership'</span>]
};

<span class="hljs-keyword">const</span> ravenclaw: House = {
  name: <span class="hljs-string">'Ravenclaw'</span>,
  traits: [<span class="hljs-string">'intelligence'</span>, <span class="hljs-string">'learning'</span>]
};

<span class="hljs-keyword">const</span> hufflepuff: House = {
  name: <span class="hljs-string">'Hufflepuff'</span>,
  traits: [<span class="hljs-string">'hard work'</span>, <span class="hljs-string">'patience'</span>]
};

<span class="hljs-keyword">const</span> houses: House[] = [
  gryffindor,
  slytherin,
  ravenclaw,
  hufflepuff
];
</code></pre>
<p>I want to keep it simple, so the <code>House</code> type has only the <code>name</code> and the <code>traits</code>, a list of possible traits from people related to the house.</p>
<p>And then, I create each house and added all of them to the <code>houses</code> list.</p>
<p>Great! Now I'll build the <code>Person</code> type. A person can be a witch or a muggle.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Witch = {
  name: <span class="hljs-built_in">string</span>;
  trait: <span class="hljs-built_in">string</span>;
    magicFamily: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">type</span> Muggle = {
  name: <span class="hljs-built_in">string</span>;
    trait: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
}
</code></pre>
<p>And this is the part we combine these two different types using the union type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Person = Muggle | Witch;
</code></pre>
<p>Using the intersection type, the <code>Person</code> type has all properties from <code>Muggle</code> or all from  <code>Witch</code>.</p>
<p>So now, if I create a <code>Muggle</code>, I need just the name, the trait, and the email:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> hermione: Muggle = {
  name: <span class="hljs-string">'Hermione Granger'</span>,
    trait: <span class="hljs-string">'bravery'</span>,
  email: <span class="hljs-string">'hermione@mail.com'</span>
};
</code></pre>
<p>If I create a <code>Witch</code>, I need the name, the trait, and the magic family name:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> harry: Witch = {
  name: <span class="hljs-string">'Harry Potter'</span>,
  trait: <span class="hljs-string">'courage'</span>,
  magicFamily: <span class="hljs-string">'Potter'</span>
};
</code></pre>
<p>And if I create a <code>Person</code>, I need at least the <code>name</code> and the <code>trait</code> properties from <code>Muggle</code> and <code>Witch</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> tk: Person = {
  name: <span class="hljs-string">'TK'</span>,
  email: <span class="hljs-string">'tk@mail.com'</span>,
  trait: <span class="hljs-string">'learning'</span>,
  magicFamily: <span class="hljs-string">'Kinoshita'</span>
};
</code></pre>
<p>The <code>chooseHouse</code> is very simple. We just pas the houses and the person. Based on the person trait, the function will return the chosen house:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">chooseHouse</span>(<span class="hljs-params">houses: House[], person: Person</span>) </span>{
  <span class="hljs-keyword">return</span> houses.find(<span class="hljs-function">(<span class="hljs-params">house</span>) =&gt;</span> house.traits.includes(person.trait))
}
</code></pre>
<p>And applying all the people we created:</p>
<pre><code class="lang-typescript">chooseHouse(houses, harry); <span class="hljs-comment">// { name: 'Gryffindor', traits: ['courage', 'bravery'] }</span>
chooseHouse(houses, hermione); <span class="hljs-comment">// { name: 'Gryffindor', traits: ['courage', 'bravery'] }</span>
chooseHouse(houses, tk); <span class="hljs-comment">// { name: 'Ravenclaw', traits: ['intelligence', 'learning'] }</span>
</code></pre>
<p>Nice!</p>
<p>The intersection type is a bit different, but it can also be used to combine existing types.</p>
<p>When I was implementing a web app to <a target="_blank" href="https://github.com/leandrotk/ux-studies">apply my studies on UX</a>, I needed to create a prop type for the Image component.</p>
<p>I had the type <code>ImageUrl</code> from the product type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageUrl = {
  imageUrl: <span class="hljs-built_in">string</span>;
};
</code></pre>
<p>And the <code>ImageAttr</code> to represent all the attributes for the image:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageAttr = {
  imageAlt: <span class="hljs-built_in">string</span>;
  width?: <span class="hljs-built_in">string</span>
};
</code></pre>
<p>But the props expected all this information in the component. Intersection type for the rescue!</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageProps = ImageUrl &amp; ImageAttr;
</code></pre>
<p>Simple as that. So now, the component needs all these properties. The type looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageProps = {
  imageUrl: <span class="hljs-built_in">string</span>;
  imageAlt: <span class="hljs-built_in">string</span>;
  width?: <span class="hljs-built_in">string</span>
};
</code></pre>
<p>And we can use this type this way:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> imageProps: ImageProps = {
  imageUrl: <span class="hljs-string">'www.image.com'</span>,
  imageAlt: <span class="hljs-string">'an image'</span>,
};

<span class="hljs-keyword">const</span> imagePropsWithWidth: ImageProps = {
  imageUrl: <span class="hljs-string">'www.image.com'</span>,
  imageAlt: <span class="hljs-string">'an image'</span>,
  width: <span class="hljs-string">'100%'</span>
};
</code></pre>
<p>Nice! One more concept to reuse and compose types.</p>
<p>I also find the <code>Pick</code> type very interesting and useful. We have other <a target="_blank" href="https://leandrotk.github.io/tk/2020/05/typescript-learnings-interesting-types/index.html">interesting types</a> that we could write here, but the idea here is to understand that we can compose type and there is no limit to reuse types. If you're interested in study other types, take a look at this post I wrote: <a target="_blank" href="https://leandrotk.github.io/tk/2020/05/typescript-learnings-interesting-types/index.html">TypeScript Learnings: Interesting Types</a>.</p>
<h2 id="heading-tooling">Tooling</h2>
<p>When you <code>npm install typescript</code>, you don't just get the compiler, you get the language service API, a standalone server called tsserver that editors can run to provide autocompletion, go-to, and other cool features.</p>
<p>These features are what some people from the TypeScript team call developer productivity tools like smart errors when type checking and IntelliSense (code completion, hover info, signature information). We look at these features throughout the whole article, but I want to make a special topic to talk about it.</p>
<p>The TypeScript type checker is powerful in the sense that it can infer types and provide information to some possible issues. Example: It inferred that the city is a string. And the <code>uppercase</code> is used the wrong way. As it knows it is a string, it also tries to find a possible method that the engineer is looking for.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> city = <span class="hljs-string">'Tokyo'</span>;
city.toUppercase();
<span class="hljs-comment">// Property 'toUppercase' does not exist on type</span>
<span class="hljs-comment">// 'string'. Did you mean 'toUpperCase'?</span>
</code></pre>
<p>In this case, the compiler is really smart, because it finds exatcly what we wanted.</p>
<p>It also works for objects:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> people = [
  { name: <span class="hljs-string">'TK'</span>, age: <span class="hljs-number">24</span> },
  { name: <span class="hljs-string">'Kaio'</span>, age: <span class="hljs-number">12</span> },
  { name: <span class="hljs-string">'Kazumi'</span>, age: <span class="hljs-number">31</span> },
];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> person <span class="hljs-keyword">of</span> people) {
  <span class="hljs-built_in">console</span>.log(person.agi);
  <span class="hljs-comment">// Property 'agi' does not exist on type '{ name: string; age: number; }'</span>
}
</code></pre>
<p>With the static types, the tooling can provide a great developer experience with code completion, hover info to show defined types, and signature information for methods and other data.</p>
<p>If you type: <code>'TK'.</code>, the editor will show all the possible methods for the string object. The compiler knows it is a string. And it knows the methods from the <code>String</code> prototype. But it also provides the method signature. This is very interesting because we don't necessarily need to go to the docs. The "docs" is already in our code editor.</p>
<p>It's an awesome experience while coding.</p>
<p>The type definition "on hover" is another thing that we saw earlier in this article. Let the compiler infer the types implicitly and you won't lose the type documentation. Using the hover in the object, the IDE or editor will always be able to show the type definition.</p>
<p>Another interesting thing is that TypeScript will not only flag what could go wrong on runtime, but it also helps to find code that doesn't do what you intend.</p>
<p>Imagine we have a function to open a snackbar if it is still closed. It would verify the status of the snackbar. If it is closed, just call another function to open it.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> buildSnackbar = <span class="hljs-function">(<span class="hljs-params">status: SnackbarStatus</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (status.isClosed) {
    openSnackbar();
  }
};
</code></pre>
<p>And the type information for this snackbar is:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> SnackbarStatus = {
  isClosed: <span class="hljs-built_in">boolean</span>;
};
</code></pre>
<p>What happens if I call this function like this:</p>
<pre><code class="lang-typescript">buildSnackbar({ isclosed: <span class="hljs-literal">true</span> });
</code></pre>
<p>It won't break in runtime, because the <code>status</code> object has no <code>isClosed</code> attribute and the <code>undefined</code> object is a <code>falsy</code> value, so it will skip the if condition and not call the <code>openSnackbar</code> function. No runtime error. But probably it will behavior different than the expected.</p>
<p>In TypeScript, the compiler will give some hints to make it works properly. First it will show this error:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Argument of type '{ isclosed: boolean; }' is not assignable to</span>
<span class="hljs-comment">// parameter of type 'SnackbarStatus'.</span>
</code></pre>
<p><code>isclosed</code> with downcased <code>C</code> is not assignable to the type. It's not defined there. This is the first hint to make you correct your code.</p>
<p>The second is even better:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Object literal may only specify known properties,</span>
<span class="hljs-comment">// but 'isclosed' does not exist in type 'SnackbarStatus'.</span>
<span class="hljs-comment">// Did you mean to write 'isClosed'?</span>
</code></pre>
<p>It tells exactly what you probably need to do: rename the <code>isclosed</code> to <code>isClosed</code>.</p>
<p>We can talk a lot of things about the tooling about I think this is the main part.</p>
<p>My suggestion to learn more about this is to just code in TypeScript and "have a conversation" with the compiler. Read the errors. Play with the hover. See the autocompletion. Understand the method signatures. It's really a productive way to code.</p>
<h2 id="heading-tips-amp-learnings">Tips &amp; Learnings</h2>
<p>As the article is coming to an end, I want to just add some final thoughts, learnings, and tips to help you in your journey learning TypeScript or just applying it in your projects.</p>
<ul>
<li>Really read the type error: this will help you better understand the issue and the types.</li>
<li><code>strictNullChecks</code> and <code>noImplicitAny</code> can be very helpful in finding bugs. Enable this as soon as possible in your project. Use <code>strictNullChecks</code> to prevent “undefined is not an object”-style runtime errors. Use <code>noImplicitAny</code> to type the source code to give more type information for the compiler.</li>
<li>Together with the compiler's configurations, I always recommend being very precise about your types. Mainly with the values that occur only in runtime like an API response. Correctness is important to catch as many bugs as possible in compile time.</li>
<li>Understand the difference between runtime and compile time: types only affect in compile type. It runs the type checker and then compiles to JavaScript. The JavaScript source code doesn't use any type of references or type operations.</li>
<li>Learn about utility types. We talked more specifically about the <code>Readonly</code> in the immutability in compile time, but TypeScript has a box of helpers like <code>Required</code>, <code>Pick</code>, and many more.</li>
<li>If possible, prefer letting the compiler infers the types for you. Most of the types and returning types are redundant. The TypeScript compiler is very smart in this area. If not possible, you can always add type annotations. And leave the type assertions as the last option.</li>
<li>As you're writing code, take a look at the tooling. The design of the tooling provided in an IDE is amazing. The IntelliSense and type checking provide a really good experience.</li>
</ul>
<p>This post was originally published at <a target="_blank" href="https://leandrotk.github.io/tk/2020/07/a-mental-model-to-think-in-typescript/index.html">TK's blog</a>. And you can find more content like this in my blog at <a target="_blank" href="https://leandrotk.github.io/tk/">https://leandrotk.github.io/tk</a>.</p>
<p>You can also follow me on <a target="_blank" href="https://twitter.com/leandrotk_">Twitter</a> and <a target="_blank" href="https://github.com/leandrotk">GitHub</a>.</p>
<h1 id="heading-resources">Resources</h1>
<p>I compiled (pun very much intended!) a bunch of resources to help you learn more about programming languages, type systems, and the type mental model.</p>
<p>Also, if you found the examples on this post useful, I added all of them this repository: <a target="_blank" href="https://github.com/leandrotk/thinking-in-types">Thinking in Types</a>. So you can fork and play with it.</p>
<h3 id="heading-type-systems">Type Systems</h3>
<ul>
<li><a target="_blank" href="https://www.typescriptlang.org/docs/handbook/type-compatibility.html">Type Compatibility</a></li>
<li><a target="_blank" href="https://medium.com/@thejameskyle/type-systems-structural-vs-nominal-typing-explained-56511dd969f4">Type Systems: Structural vs. Nominal typing explained</a></li>
<li><a target="_blank" href="https://yakovfain.com/2018/07/11/learning-typescript-structural-vs-nominal-typing-system/">Learning TypeScript: Structural vs nominal typing systems</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=GqmsQeSzMdw&amp;feature=youtu.be">Constraints Liberate, Liberties Constrain — Runar Bjarnason</a></li>
<li><a target="_blank" href="https://www.no.lol/2019-12-27-type-narrowing/">Type Narrowing in TypeScript</a></li>
<li><a target="_blank" href="https://2ality.com/2020/06/type-guards-assertion-functions-typescript.html">TypeScript: narrowing types via type guards and assertion functions</a></li>
<li><a target="_blank" href="https://leandrotk.github.io/tk/2020/05/typescript-learnings-interesting-types/index.html">TypeScript Learnings: Interesting Types</a></li>
</ul>
<h3 id="heading-tooling-amp-developer-experience">Tooling &amp; Developer Experience</h3>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=fnTEZk-oECM">Advanced TypeScript tooling at scale</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=4C4wCGcsiT0">Type Systems &amp; Props Design</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=wSdV1M7n4gQ">Anders Hejlsberg on Modern Compiler Construction</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=f6TCB61fDwY">TypeScript Compiler explained by the Author Anders Hejlsberg</a></li>
</ul>
<h3 id="heading-compile-time-vs-runtime">Compile time vs Runtime</h3>
<ul>
<li><a target="_blank" href="https://stackoverflow.com/questions/846103/runtime-vs-compile-time">Compile time vs Runtime</a></li>
<li><a target="_blank" href="https://stackoverflow.com/questions/9471837/what-is-the-difference-between-run-time-error-and-compiler-error">Compile error vs Runtime error</a></li>
<li><a target="_blank" href="https://stackoverflow.com/a/51132333/3159162">Value space and Type space</a></li>
<li><a target="_blank" href="https://www.typescriptlang.org/play">A playground tool to play with TypeScript and see the JavaScript output</a></li>
</ul>
<h3 id="heading-best-practices">Best Practices</h3>
<ul>
<li><a target="_blank" href="https://engineering.zalando.com/posts/2019/02/typescript-best-practices.html">TypeScript Best Practices</a></li>
<li><a target="_blank" href="https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html">Do's and Don'ts for General Types</a></li>
</ul>
<h3 id="heading-books">Books</h3>
<ul>
<li><a target="_blank" href="https://www.goodreads.com/book/show/48920810-programming-with-types">Programming with Types Book</a></li>
<li><a target="_blank" href="https://www.goodreads.com/book/show/48570456-effective-typescript">Effective TypeScript: 62 Specific Ways to Improve Your TypeScript Book</a></li>
<li><a target="_blank" href="https://thinkingwithtypes.com/">Thinking with Types</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Functional Components in React ]]>
                </title>
                <description>
                    <![CDATA[ By Cristian Salcescu Have you wondered how to create a component in React?  To answer, it is as simple as creating a function returning an HTML-like syntax. import React from 'react'; function Counter({n}) {   return (     <div>{n}</div>   ); } exp... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-few-questions-on-functional-components/</link>
                <guid isPermaLink="false">66d45e01230dff01669057ad</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 03 May 2020 08:11:26 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/05/kelvyn-ornettte-sol-marte-86DcFWVMp0g-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Cristian Salcescu</p>
<p>Have you wondered how to create a component in React? </p>
<p>To answer, it is as simple as creating a function returning an HTML-like syntax.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params">{n}</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{n}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre>
<p>Now let’s see what happened in the code above.  <code>Counter</code> is a function that transforms a number into HTML. And if you look more carefully, <code>Counter</code> is a pure function. That’s right, the kind of function that returns the result based on its inputs and has no side-effects. </p>
<p>This explanation comes with a new question. What is a side-effect?</p>
<p>In short, a side-effect is any modification on the environment outside the function or any read information from the outside environment that can change.</p>
<p>You may have noticed that I used the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructuring assignment syntax</a> in the parameter list to extract out the <code>n</code> input number. That’s because components take as input a single object called “props” that has all the properties sent to them. </p>
<p>Here is how the <code>n</code> parameter can be set from any other component:</p>
<pre><code class="lang-js">&lt;Counter n={<span class="hljs-number">1</span>} /&gt;
</code></pre>
<p>In a sense, this syntax can be imagined like a function call <code>Counter({n: 1})</code>. Isn’t that right?</p>
<p>Let’s continue our journey.</p>
<p>Can functional components have state? As the component name suggested I want to store and change a counter. What if we just declare a variable holding a number inside the component? Will it work?</p>
<p>Let’s find out.</p>
<p>I will start by declaring the variable inside the functional component.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{n}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre>
<p>Now let’s add the function that increments the number and logs it to the console. I will use the function as the event handler for the click event.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">increment</span>(<span class="hljs-params"></span>)</span>{
    n = n + <span class="hljs-number">1</span>;
    <span class="hljs-built_in">console</span>.log(n)
  }

  <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">span</span>&gt;</span>{n}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{increment}</span>&gt;</span>Increment <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre>
<p>If we look at the console we see that the number is actually incremented, but that is not reflected on the screen. Any ideas?</p>
<p>You got it right … we need to change the number, but we need also to re-render it on the screen.</p>
<p>Here is where the utility function from <a target="_blank" href="https://reactjs.org/docs/hooks-intro.html">React Hooks</a> comes into play. By the way, these utility functions are called hooks and they start with the word “use”. We are going to use one of them, <a target="_blank" href="https://reactjs.org/docs/hooks-state.html">useState</a>. I will log also the “re-render” text to console to see how many times the <code>Counter</code> function is actually called.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [n, setN] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'re-render'</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">increment</span>(<span class="hljs-params"></span>)</span>{
    setN(n + <span class="hljs-number">1</span>);
    <span class="hljs-built_in">console</span>.log(n)
  }

  <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">span</span>&gt;</span>{n}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{increment}</span>&gt;</span>Increment <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre>
<p>Let’s read what <code>useState()</code> does.</p>
<p><strong>What does</strong> <code>**useState**</code> <strong>return?</strong> It returns a pair of values: the current state and a function that updates it.</p>
<p>In our case <code>n</code> is the current state and <code>setN()</code> is the function that updates it. Have you checked the console to see how many times the “re-render” text is displayed? I will leave that for you to find out.</p>
<p>We can update the state not only by setting the new value but also by providing a function that returns the new value.</p>
<p>In our case, the function that provides the new value will be called <code>increment()</code>. As you see, <code>increment()</code> is a pure function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">increment</span>(<span class="hljs-params">n</span>)</span>{
  <span class="hljs-keyword">return</span> n + <span class="hljs-number">1</span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [n, setN] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>{n}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> 
         <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setN(increment)}&gt;
           Increment 
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre>
<p>To understand what <code>setN(increment)</code> does, let’s read the documentation.</p>
<p><em>Passing an update function allows you to access the current state value inside the updater.</em></p>
<p>OK so <code>increment()</code> gets called with the current <code>n</code> state and it is used to compute the new state value.</p>
<h1 id="heading-final-thoughts">Final Thoughts</h1>
<p>Let’s summarize what we found out.</p>
<p>In React we can simply define a component using a function that returns an HTML-like syntax.</p>
<p>React Hooks enables us to define state into such functional components.</p>
<p>And last but not least, we finally got rid of <code>this</code> pseudo-parameter in components. Maybe you have noticed that <code>this</code> becomes annoying by changing context when you don't expect it. No worries about that. We are not going to use <code>this</code> in functional components.</p>
<p>If you've made it this far you can also take a look at my books.</p>
<p><a target="_blank" href="https://read.amazon.com/kp/embed?asin=B07PBQJYYG&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=cm_sw_r_kb_dp_cm5KCbE5BDJGE"><strong>Discover Functional JavaScript</strong></a> was named one of the <a target="_blank" href="https://bookauthority.org/books/best-functional-programming-books"><strong>best Functional Programming books by BookAuthority</strong></a><strong>!</strong></p>
<p>For more on applying functional programming techniques to React take a look at <strong><a target="_blank" href="https://www.amazon.com/dp/B088FZQ1XN">Functional React</a>.</strong></p>
<p>Learn <strong>functional React</strong>, in a project-based way, with <a target="_blank" href="https://read.amazon.com/kp/embed?asin=B0846NRJYR&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=cm_sw_r_kb_dp_o.hlEbDD02JB2"><strong>Functional Architecture with React and Redux</strong></a><strong>.</strong></p>
<p><a target="_blank" href="https://twitter.com/cristi_salcescu">Tweet me your feedback</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
