<?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[ functions - 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[ functions - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 30 May 2026 14:17:29 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/functions/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How Passing by Object Reference Works in Python ]]>
                </title>
                <description>
                    <![CDATA[ If you've ever modified a variable inside a Python function and been surprised or confused by what happened to it outside the function, you're not alone. This tripped me up for a long time. Coming fro ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-passing-by-object-reference-works-in-python/</link>
                <guid isPermaLink="false">69c5415810e664c5dadbf6e0</guid>
                
                    <category>
                        <![CDATA[ python beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mokshita V P ]]>
                </dc:creator>
                <pubDate>Thu, 26 Mar 2026 14:23:20 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/0fb11934-22c6-4304-948c-54c7d423c79d.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've ever modified a variable inside a Python function and been surprised or confused by what happened to it outside the function, you're not alone. This tripped me up for a long time.</p>
<p>Coming from tutorials that talked about "call by value" and "call by reference," I assumed Python must follow one of those two models. It doesn't. Python does something slightly different, and once you understand it, a lot of previously confusing behavior will suddenly click.</p>
<p>In this article, you'll learn:</p>
<ul>
<li><p>What calling by value and calling by reference mean</p>
</li>
<li><p>How other languages like C handle this</p>
</li>
<li><p>What Python actually does (passing by object reference)</p>
</li>
<li><p>How mutable and immutable types affect behavior inside functions</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-call-by-value-and-call-by-reference-explained">Call by Value and Call by Reference Explained</a></p>
</li>
<li><p><a href="#heading-how-it-works-in-c-with-examples">How It Works in C (with Examples)</a></p>
</li>
<li><p><a href="#heading-what-python-does-instead">What Python Does Instead</a></p>
</li>
<li><p><a href="#heading-mutable-vs-immutable-types">Mutable vs Immutable Types</a></p>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-call-by-value-and-call-by-reference-explained">Call by Value and Call by Reference Explained</h2>
<p>Before we get to Python, let's quickly define these two terms.</p>
<p><strong>Call by value</strong> means a copy of the variable is passed to the function. Whatever you do to it inside the function, the original stays unchanged.</p>
<p><strong>Call by reference</strong> means the actual memory location of the variable is passed. Changes inside the function directly affect the original variable.</p>
<p>Many languages support one or both of these models. Python, however, uses neither – at least not in the traditional sense.</p>
<h3 id="heading-how-it-works-in-c-with-examples">How It Works in C (with Examples)</h3>
<p>C is a good example of a language that supports both models explicitly.</p>
<p>Here's how you call by value in C. The original variable is unaffected:</p>
<pre><code class="language-c">#include &lt;stdio.h&gt;

void modify(int *n) {

*n = *n + 10;

printf("Inside function: %d\n", *n); }

int main() {

int x = 5;

modify(&amp;x);

printf("Outside function: %d\n", x);

return 0; }
</code></pre>
<p>Output:</p>
<p>Inside function: 15</p>
<p>Outside function: 15 ← original changed!</p>
<p>In C, you explicitly choose the behavior by deciding whether to pass a pointer or a plain value. Python doesn't give you that choice, but what it does instead is actually quite logical.</p>
<h2 id="heading-what-python-does-instead">What Python Does Instead</h2>
<p>Python uses a model called <strong>passing by object reference</strong> (sometimes called passing by assignment).</p>
<p>When you pass a variable to a function in Python, you're passing a reference to the object that variable points to, not a copy of the value, and not the variable itself.</p>
<p>What happens next depends entirely on whether that object is <strong>mutable</strong> (can be changed in place) or <strong>immutable</strong> (cannot be changed in place).</p>
<h3 id="heading-mutable-vs-immutable-types">Mutable vs Immutable Types</h3>
<p><strong>Immutable types</strong> in Python include <code>int</code>, <code>float</code>, <code>str</code>, and <code>tuple</code>. These objects cannot be modified in place. When you "change" one inside a function, Python creates a brand new object and the original is left untouched.</p>
<pre><code class="language-python">def modify_number(n):
     n = n + 10
     print("Inside function:", n)

x = 5

modify_number(x)

print("Outside function:", x)
</code></pre>
<p>Output:</p>
<p>Inside function: 15</p>
<p>Outside function: 15 ← original unchanged</p>
<p><strong>Mutable types</strong> include <code>list</code>, <code>dict</code>, and <code>set</code>. These can be changed in place. When you modify one inside a function, you're modifying the same object the caller is holding a reference to.</p>
<pre><code class="language-python">def modify_list(items):

    items.append(99)

    print("Inside function:", items)

my_list = [1, 2, 3]

modify_list(my_list)

print("Outside function:", my_list)
</code></pre>
<p>Output:</p>
<p>Inside function: [1, 2, 3, 99]</p>
<p>Outside function: [1, 2, 3, 99] ← original changed!</p>
<p>This is the key insight: Python doesn't decide behavior based on how you pass something, it decides based on what type of object you're passing.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Python doesn't use call by value or call by reference. It <strong>passes by object reference</strong>, where the function receives a reference to the object, and whether that object can be modified in place determines what happens next.</p>
<p>To recap:</p>
<ul>
<li><p><strong>Immutable types</strong> (<code>int</code>, <code>str</code>, <code>tuple</code>): a new object is created inside the function, original stays the same</p>
</li>
<li><p><strong>Mutable types</strong> (<code>list</code>, <code>dict</code>, <code>set</code>): the original object is modified directly</p>
</li>
</ul>
<p>Once this clicked for me, a lot of the "why is Python doing this?" moments started making sense. If you're just getting started with functions in Python, keep this in the back of your mind, it'll save you a lot of debugging headaches.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Higher Order Functions in JavaScript? Explained With Examples ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript offers a powerful feature known as higher order functions (HOFs). These functions elevate your code by treating other functions as citizens of the language itself.  In simpler terms, HOFs can accept functions as arguments and even return f... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/higher-order-functions-explained/</link>
                <guid isPermaLink="false">66c4c3d1d788a9c53d88d2be</guid>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Thu, 02 May 2024 18:31:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/Ivory-and-Blue-Lavender-Aesthetic-Photo-Collage-Presentation--7-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript offers a powerful feature known as higher order functions (HOFs). These functions elevate your code by treating other functions as citizens of the language itself.  In simpler terms, HOFs can accept functions as arguments and even return functions as results. This ability allows developers to write clean, reusable, and expressive code.</p>
<p>This article comprehensively discusses higher order functions in JavaScript. We'll begin by establishing a clear understanding of HOFs, their core concepts, and the advantages they bring to your development process.  We'll then explore some of the most commonly used HOFs in JavaScript, like <code>map</code>, <code>filter</code>, and <code>reduce</code>, providing detailed explanations, syntax breakdowns, and practical examples to solidify your grasp.</p>
<h2 id="heading-what-are-higher-order-functions">What are Higher Order Functions?</h2>
<p>Higher order functions (HOFs) in JavaScript are functions that can do at least one of the following:</p>
<ul>
<li>Accept other functions as arguments.</li>
<li>Return a function as a result.</li>
</ul>
<h2 id="heading-core-concepts-of-higher-order-functions">Core concepts of Higher Order Functions</h2>
<h3 id="heading-1-accepting-functions-as-arguments">1. Accepting Functions as Arguments</h3>
<p>Higher order functions can accept other functions as arguments. This allows for dynamic behavior, where the behavior of the higher order function can be customized based on the function passed as an argument.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Higher Order Function that accepts a callback function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">higherOrderFunction</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-comment">// Performing some operations</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Executing the higher order function..."</span>);

  <span class="hljs-comment">// Calling the callback function</span>
  callback();
}

<span class="hljs-comment">// Callback function to be passed to the higher order function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Executing the callback function..."</span>);
}

<span class="hljs-comment">// Calling the higher order function with the callback function as argument</span>
higherOrderFunction(callbackFunction);
</code></pre>
<p>In this example, <code>higherOrderFunction</code> is a higher order function that accepts another function (<code>callback</code>) as an argument. When <code>higherOrderFunction</code> is called, it executes some operations and then calls the <code>callback</code> function passed to it. This allows for customizing the behavior of <code>higherOrderFunction</code> by passing different callback functions.</p>
<h3 id="heading-2-returning-functions">2. Returning Functions</h3>
<p>Higher order functions can also return functions. This enables the creation of functions dynamically based on certain conditions or parameters.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Higher Order Function that returns a function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createGreeter</span>(<span class="hljs-params">greeting</span>) </span>{
  <span class="hljs-comment">// Returning a new function</span>
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${greeting}</span>, <span class="hljs-subst">${name}</span>!`</span>);
  };
}

<span class="hljs-comment">// Creating a greeter function with a specific greeting</span>
<span class="hljs-keyword">const</span> greetHello = createGreeter(<span class="hljs-string">"Hello"</span>);
greetHello(<span class="hljs-string">"John"</span>); <span class="hljs-comment">// Output: Hello, John!</span>

<span class="hljs-comment">// Creating another greeter function with a different greeting</span>
<span class="hljs-keyword">const</span> greetGoodbye = createGreeter(<span class="hljs-string">"Goodbye"</span>);
greetGoodbye(<span class="hljs-string">"Alice"</span>); <span class="hljs-comment">// Output: Goodbye, Alice!</span>
</code></pre>
<p>In this example, <code>createGreeter</code> is a higher order function that returns a new function. The returned function (<code>greetHello</code> and <code>greetGoodbye</code>) takes a <code>name</code> parameter and logs a greeting message with the specified greeting passed to <code>createGreeter</code>. This allows for creating different greeter functions with different greetings dynamically.</p>
<h3 id="heading-3-abstraction">3. Abstraction</h3>
<p>Higher order functions promote abstraction by encapsulating common patterns or behaviors into reusable functions. This leads to cleaner and more modular code.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Higher Order Function for performing a specified operation on each element of an array</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">performOperationOnArray</span>(<span class="hljs-params">array, operation</span>) </span>{
  <span class="hljs-keyword">return</span> array.map(operation);
}

<span class="hljs-comment">// Callback function for doubling each element of an array</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">double</span>(<span class="hljs-params">number</span>) </span>{
  <span class="hljs-keyword">return</span> number * <span class="hljs-number">2</span>;
}

<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-keyword">const</span> doubledNumbers = performOperationOnArray(numbers, double);
<span class="hljs-built_in">console</span>.log(doubledNumbers); <span class="hljs-comment">// Output: [2, 4, 6, 8, 10]</span>
</code></pre>
<p>In this example, <code>performOperationOnArray</code> is a higher order function that accepts an array and an <code>operation</code> function as arguments. It then applies the <code>operation</code> function to each element of the array using the <code>map</code> method and returns the result. This promotes code reusability and abstraction by allowing different operations to be performed on arrays without having to rewrite the logic for iterating over the array.</p>
<h2 id="heading-why-use-higher-order-functions">Why use Higher Order Functions?</h2>
<p>Using HOFs in JavaScript provides several advantages that can enhance the flexibility, reusability, and maintainability of your codebase. Let's explore these benefits:</p>
<h3 id="heading-code-reusability">Code Reusability</h3>
<p>HOFs promote code reusability by allowing you to abstract common patterns into reusable functions. This reduces code duplication and makes your codebase more maintainable.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: HOF for filtering elements based on a condition</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">filterArray</span>(<span class="hljs-params">array, condition</span>) </span>{
  <span class="hljs-keyword">return</span> array.filter(condition);
}

<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-comment">// Using filterArray to filter even numbers</span>
<span class="hljs-keyword">const</span> evenNumbers = filterArray(numbers, <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(evenNumbers); <span class="hljs-comment">// Output: [2, 4]</span>
</code></pre>
<p>Instead of writing a custom filtering logic each time, you can create a reusable <code>filterArray</code> function that accepts an array and a condition function. This promotes code reusability as you can use <code>filterArray</code> with different conditions to filter arrays based on various criteria.</p>
<h3 id="heading-modularity">Modularity</h3>
<p>HOFs help in breaking down complex tasks into smaller, more manageable functions, promoting modular code design.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: HOF for performing a series of operations on an array</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processArray</span>(<span class="hljs-params">array, operations</span>) </span>{
  <span class="hljs-keyword">return</span> operations.reduce(<span class="hljs-function">(<span class="hljs-params">acc, operation</span>) =&gt;</span> operation(acc), array);
}

<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-comment">// Using processArray to perform multiple operations</span>
<span class="hljs-keyword">const</span> result = processArray(numbers, [
  <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr.map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * <span class="hljs-number">2</span>),
  <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">3</span> === <span class="hljs-number">0</span>)
]);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: [6]</span>
</code></pre>
<p>By encapsulating individual operations as functions and passing them to a higher-order function like <code>processArray</code>, you can break down complex tasks into smaller, more manageable units. This promotes modular code design, making your codebase easier to understand, maintain, and extend.</p>
<h3 id="heading-flexibility">Flexibility</h3>
<p>HOFs allow for dynamic behavior by accepting functions as arguments or returning functions as results. This flexibility enables you to customize the behavior of a function at runtime.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: HOF for creating a multiplier function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createMultiplier</span>(<span class="hljs-params">factor</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">number</span>) </span>{
    <span class="hljs-keyword">return</span> number * factor;
  };
}

<span class="hljs-keyword">const</span> double = createMultiplier(<span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(double(<span class="hljs-number">5</span>)); <span class="hljs-comment">// Output: 10</span>
</code></pre>
<p>By returning a function from <code>createMultiplier</code>, you can dynamically generate a new function with a specific multiplication factor. This provides flexibility as you can create multiple multiplier functions with different factors without having to redefine the logic each time.</p>
<h2 id="heading-popular-higher-order-functions-in-javascript">Popular Higher Order Functions in JavaScript</h2>
<p>Let's explore the popular higher order functions in JavaScript along with their descriptions, syntax, and practical usage examples:</p>
<h3 id="heading-1-arrayprototypemap">1. Array.prototype.map()</h3>
<p>The <code>map()</code> method creates a new array by calling a provided function on every element in the calling array.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newArray = array.map(callback(currentValue, index, array));
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Iterating over arrays and transforming elements.</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Doubling each number in an array</span>
<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-keyword">const</span> doubledNumbers = numbers.map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(doubledNumbers); <span class="hljs-comment">// Output: [2, 4, 6, 8, 10]</span>

<span class="hljs-comment">// Example 2: Converting an array of strings to uppercase</span>
<span class="hljs-keyword">const</span> words = [<span class="hljs-string">"hello"</span>, <span class="hljs-string">"world"</span>, <span class="hljs-string">"javascript"</span>];
<span class="hljs-keyword">const</span> uppercaseWords = words.map(<span class="hljs-function"><span class="hljs-params">word</span> =&gt;</span> word.toUpperCase());
<span class="hljs-built_in">console</span>.log(uppercaseWords); <span class="hljs-comment">// Output: ["HELLO", "WORLD", "JAVASCRIPT"]</span>
</code></pre>
<h3 id="heading-2-arrayprototypefilter">2. Array.prototype.filter()</h3>
<p>The <code>filter()</code> method creates a new array with all elements that pass the test implemented by the provided function.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newArray = array.filter(callback(element, index, array));
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Creating new arrays based on specific conditions.</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Filtering even numbers from an array</span>
<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-keyword">const</span> evenNumbers = numbers.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(evenNumbers); <span class="hljs-comment">// Output: [2, 4]</span>

<span class="hljs-comment">// Example 2: Filtering words longer than 5 characters</span>
<span class="hljs-keyword">const</span> words = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"grape"</span>, <span class="hljs-string">"kiwi"</span>, <span class="hljs-string">"orange"</span>];
<span class="hljs-keyword">const</span> longWords = words.filter(<span class="hljs-function"><span class="hljs-params">word</span> =&gt;</span> word.length &gt; <span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(longWords); <span class="hljs-comment">// Output: ["banana", "orange"]</span>
</code></pre>
<h3 id="heading-3-arrayprototypereduce">3. Array.prototype.reduce()</h3>
<p>The <code>reduce()</code> method applies a function against an accumulator and each element in the array to reduce it to a single value.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = array.reduce(callback(accumulator, currentValue, index, array), initialValue);
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Accumulating a single value from an array.</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Finding the sum of numbers in an array</span>
<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-keyword">const</span> sum = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">acc, num</span>) =&gt;</span> acc + num, <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(sum); <span class="hljs-comment">// Output: 15</span>

<span class="hljs-comment">// Example 2: Finding the average of numbers in an array</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>, <span class="hljs-number">50</span>];
<span class="hljs-keyword">const</span> average = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">acc, num, index, array</span>) =&gt;</span> {
  acc += num;
  <span class="hljs-keyword">if</span> (index === array.length - <span class="hljs-number">1</span>) {
    <span class="hljs-keyword">return</span> acc / array.length;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> acc;
  }
}, <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(average); <span class="hljs-comment">// Output: 30</span>
</code></pre>
<h3 id="heading-4-arrayprototypeforeach">4. Array.prototype.forEach()</h3>
<p>The <code>forEach()</code> method executes a provided function once for each array element.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript">array.forEach(callback(currentValue, index, array));
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Iterating over arrays and performing side effects (e.g., logging).</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Logging each element of an array</span>
<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>];
numbers.forEach(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(num));

<span class="hljs-comment">// Example 2: Capitalizing and logging each word of an array</span>
<span class="hljs-keyword">const</span> words = [<span class="hljs-string">"hello"</span>, <span class="hljs-string">"world"</span>, <span class="hljs-string">"javascript"</span>];
words.forEach(<span class="hljs-function"><span class="hljs-params">word</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(word.toUpperCase()));
</code></pre>
<h3 id="heading-5-arrayprototypesome">5. Array.prototype.some()</h3>
<p>The <code>some()</code> method tests whether at least one element in the array passes the test implemented by the provided function.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = array.some(callback(element, index, array));
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Checking if at least one element in an array meets a condition.</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Checking if any number in the array is greater than 10</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">5</span>, <span class="hljs-number">8</span>, <span class="hljs-number">12</span>, <span class="hljs-number">7</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> isAnyNumberGreaterThan10 = numbers.some(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num &gt; <span class="hljs-number">10</span>);
<span class="hljs-built_in">console</span>.log(isAnyNumberGreaterThan10); <span class="hljs-comment">// Output: true</span>

<span class="hljs-comment">// Example 2: Checking if any word in the array starts with "a"</span>
<span class="hljs-keyword">const</span> words = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"grape"</span>, <span class="hljs-string">"kiwi"</span>, <span class="hljs-string">"orange"</span>];
<span class="hljs-keyword">const</span> startsWithA = words.some(<span class="hljs-function"><span class="hljs-params">word</span> =&gt;</span> word.startsWith(<span class="hljs-string">"a"</span>));
<span class="hljs-built_in">console</span>.log(startsWithA); <span class="hljs-comment">// Output: true</span>
</code></pre>
<h3 id="heading-6-arrayprototypeevery">6. Array.prototype.every()</h3>
<p>The <code>every()</code> method tests whether all elements in the array pass the test implemented by the provided function.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = array.every(callback(element, index, array));
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Checking if all elements in an array meet a condition.</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Checking if all numbers in the array are positive</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">5</span>, <span class="hljs-number">8</span>, <span class="hljs-number">12</span>, <span class="hljs-number">7</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> areAllNumbersPositive = numbers.every(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num &gt; <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(areAllNumbersPositive); <span class="hljs-comment">// Output: true</span>

<span class="hljs-comment">// Example 2: Checking if all words in the array have length greater than 3</span>
<span class="hljs-keyword">const</span> words = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"grape"</span>, <span class="hljs-string">"kiwi"</span>, <span class="hljs-string">"orange"</span>];
<span class="hljs-keyword">const</span> allWordsHaveLengthGreaterThan3 = words.every(<span class="hljs-function"><span class="hljs-params">word</span> =&gt;</span> word.length &gt; <span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(allWordsHaveLengthGreaterThan3); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>These popular higher order functions in JavaScript provide powerful tools for working with arrays, enabling you to perform various operations such as mapping, filtering, reducing, iterating, and checking conditions with ease and flexibility.</p>
<h2 id="heading-advanced-techniques-with-higher-order-functions">Advanced Techniques with Higher Order Functions</h2>
<h3 id="heading-1-function-composition-chaining-hofs">1. Function Composition (Chaining HOFs)</h3>
<p>Function composition involves chaining multiple higher order functions together to create more complex operations or transformations.</p>
<p><strong>Example:</strong></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-comment">// Chaining map() and filter() to get even numbers squared</span>
<span class="hljs-keyword">const</span> result = numbers
  .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-comment">// Filter even numbers</span>
  .map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * num); <span class="hljs-comment">// Square each number</span>
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: [4, 16]</span>
</code></pre>
<p>In this example, we chained the <code>filter()</code> and <code>map()</code> functions together. First, <code>filter()</code> is used to filter out even numbers, and then <code>map()</code> squares each of the filtered numbers. This creates a pipeline of operations, allowing us to perform complex transformations in a concise and readable manner.</p>
<h3 id="heading-2-creating-custom-hofs">2. Creating Custom HOFs</h3>
<p>You can create custom higher order functions tailored to your specific requirements, encapsulating common patterns or behaviors into reusable functions.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Custom HOF for filtering based on multiple conditions</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">customFilter</span>(<span class="hljs-params">array, conditionFn</span>) </span>{
  <span class="hljs-keyword">return</span> array.filter(conditionFn);
}

<span class="hljs-comment">// Usage</span>
<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-keyword">const</span> evenGreaterThanTwo = customFilter(numbers, <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> &amp;&amp; num &gt; <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(evenGreaterThanTwo); <span class="hljs-comment">// Output: [4]</span>
</code></pre>
<p>In this example, <code>customFilter</code> is a custom higher order function that accepts an array and a condition function. It filters the array based on the condition specified in the <code>conditionFn</code>. This allows for creating custom filtering logic tailored to specific requirements.</p>
<h3 id="heading-3-hofs-and-functional-programming-paradigms">3. HOFs and Functional Programming Paradigms:</h3>
<p>Higher order functions are fundamental to functional programming paradigms, emphasizing the use of pure functions, immutability, and declarative programming style.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Functional programming paradigm using HOFs</span>
<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-comment">// Using reduce() for summing numbers</span>
<span class="hljs-keyword">const</span> sum = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">acc, num</span>) =&gt;</span> acc + num, <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(sum); <span class="hljs-comment">// Output: 15</span>

<span class="hljs-comment">// Using map() for doubling numbers</span>
<span class="hljs-keyword">const</span> doubled = numbers.map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(doubled); <span class="hljs-comment">// Output: [2, 4, 6, 8, 10]</span>
</code></pre>
<p>In this example, we demonstrate functional programming paradigms using higher order functions. The <code>reduce()</code> function is used for summing numbers, emphasizing immutability and accumulation, while the <code>map()</code> function is used for doubling numbers, promoting declarative and pure functional style.</p>
<h2 id="heading-benefits-of-hofs-in-writing-cleaner-and-more-declarative-code">Benefits of HOFs in Writing Cleaner and More Declarative Code</h2>
<p>Higher order functions enable writing cleaner, more declarative, and expressive code by promoting code reuse, modularity, and functional programming principles.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Declarative code using HOFs</span>
<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-comment">// Using map() for squaring each number</span>
<span class="hljs-keyword">const</span> squared = numbers.map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * num);
<span class="hljs-built_in">console</span>.log(squared); <span class="hljs-comment">// Output: [1, 4, 9, 16, 25]</span>
</code></pre>
<p>In this example, the <code>map()</code> function is used to square each number in the array. This approach is declarative, clearly expressing the intention of the operation without low-level imperative details, leading to cleaner and more maintainable code.</p>
<h2 id="heading-best-practices-and-considerations-when-working-with-higher-order-functions">Best Practices and Considerations when Working with Higher Order Functions</h2>
<h3 id="heading-1-choosing-the-right-hof-for-the-job">1. Choosing the Right HOF for the Job</h3>
<p>Selecting the appropriate higher order function based on the desired operation is crucial for writing efficient and readable code. Consider factors such as the specific task at hand, the expected output, and any additional requirements.</p>
<p><strong>Example:</strong></p>
<ul>
<li>Use <code>map()</code> for transforming elements in an array.</li>
<li>Use <code>filter()</code> for selecting elements based on a condition.</li>
<li>Use <code>reduce()</code> for aggregating values into a single result.</li>
<li>Use <code>forEach()</code> for performing side effects without returning a new array.</li>
</ul>
<h3 id="heading-2-avoiding-overuse-of-hofs-for-readability-concerns">2. Avoiding Overuse of HOFs for Readability Concerns</h3>
<p>While higher order functions can improve code readability and maintainability, overusing them can lead to code that is hard to understand. Use HOFs judiciously, and favor readability over excessive abstraction.</p>
<p><strong>Example:</strong></p>
<ul>
<li>Choose a simple <code>for</code> loop over chaining multiple HOFs if it enhances clarity and understanding.</li>
</ul>
<h3 id="heading-3-understanding-callback-functions-in-hofs">3. Understanding Callback Functions in HOFs:</h3>
<p>Callback functions play a vital role within higher order functions, as they define the behavior or logic to be executed by the HOF.</p>
<p><strong>Example:</strong></p>
<ul>
<li>In <code>map()</code>, the callback function defines the transformation applied to each element.</li>
<li>In <code>filter()</code>, the callback function specifies the condition for selecting elements.</li>
<li>In <code>reduce()</code>, the callback function determines how values are aggregated into the final result.</li>
</ul>
<h3 id="heading-4-writing-efficient-and-clear-callback-functions">4. Writing Efficient and Clear Callback Functions</h3>
<p>Ensure that callback functions used within HOFs are efficient, clear, and focused on a single responsibility. Write them in a way that enhances readability and promotes code maintainability.</p>
<p><strong>Example:</strong></p>
<ul>
<li>Use descriptive variable names within callback functions to improve code clarity.</li>
<li>Break down complex operations into smaller, more manageable functions if necessary.</li>
<li>Consider using arrow functions for concise and readable syntax when defining callback functions.</li>
</ul>
<h3 id="heading-5-error-handling-and-edge-cases-with-hofs">5. Error Handling and Edge Cases with HOFs</h3>
<p>Handle potential errors and edge cases gracefully when using higher order functions to ensure robustness and reliability of your code.</p>
<p><strong>Example:</strong></p>
<ul>
<li>Validate input parameters before applying higher order functions to prevent unexpected behavior.</li>
<li>Implement error handling mechanisms within callback functions to handle exceptional cases.</li>
<li>Test your HOF implementations thoroughly to cover edge cases and ensure correct behavior in all scenarios.</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Throughout this article, you've explored the core concepts of HOFs, discussed popular functions like <code>map</code> and <code>reduce</code>, and discovered advanced techniques like function composition and custom HOF creation. You've also gained valuable insights into best practices, ensuring you leverage HOFs effectively and address potential pitfalls.</p>
<p>As you move forward, keep these powerful tools in your JavaScript arsenal. By mastering HOFs, you'll write cleaner, more concise, and expressive code, propelling your development skills to new heights.  Remember, the journey doesn't end here! Explore functional programming concepts that seamlessly integrate with HOFs. There's always more to learn and discover.</p>
<p>Connect with me on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Def in C – How to Define a Function in C ]]>
                </title>
                <description>
                    <![CDATA[ Functions play a fundamental role in programming in C. They allow you to write code that is organized and easier to maintain. In this article, you'll learn the basics of defining functions in C. What is a Function in C? In programming, a function is ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-define-a-function-in-c/</link>
                <guid isPermaLink="false">661975533d607a40280a2012</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Fri, 12 Apr 2024 17:54:27 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/npxXWgQ33ZQ/upload/070d054c2dafa7e4a5f90cf0d0af30eb.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Functions play a fundamental role in programming in C. They allow you to write code that is organized and easier to maintain.</p>
<p>In this article, you'll learn the basics of defining functions in C.</p>
<h2 id="heading-what-is-a-function-in-c"><strong>What is a Function in C?</strong></h2>
<p>In programming, a function is a block of code that performs a specific task.</p>
<p>Functions take inputs, process them, perform operations, and produce an output.</p>
<p>Functions are important because they organize your code and promote code reusability.</p>
<p>Instead of writing the same code again and again and repeating yourself, you write code once and then can use it whenever you want to perform that specific task.</p>
<p>In C, there are generally two types of functions:</p>
<ul>
<li><p><strong>Standard library functions</strong>. Standard library functions are provided by the C standard library and defined in header files. Examples of standard library functions include <code>printf()</code> for printing formatted output to the console and <code>scanf()</code> for reading formatted input from the user. Both are defined in the <code>stdio.h</code> header file.</p>
</li>
<li><p><strong>User-defined functions</strong>. User-defined functions are defined by you, the programmer. These functions are tailored to your program’s needs and requirements. For example, a user-defined function may calculate the sum of two numbers or check if a number is even or odd.</p>
</li>
</ul>
<p>In this article, you will learn how to create user-defined functions.</p>
<h2 id="heading-syntax-of-functions-in-c">Syntax of Functions in C</h2>
<p>Here is the general syntax of a function in C:</p>
<pre><code class="lang-c"><span class="hljs-function">return_type <span class="hljs-title">function_name</span><span class="hljs-params">(parameter)</span> </span>{
  <span class="hljs-comment">// function body with the code to be executed</span>
  <span class="hljs-keyword">return</span> value;
}
</code></pre>
<p>Let’s break it down:</p>
<ul>
<li><p>The <code>return_type</code> lets the C compiler know the type of data of the value the function will return after its execution. It can be any valid C data type such as <code>int</code>, <code>float</code>, <code>char</code>, or <code>void</code> if the function doesn’t return a value.</p>
</li>
<li><p>The <code>function_name</code> is the name you give the function. It should be meaningful and accurately describe what the function does. You will later use this to call the function.</p>
</li>
<li><p>The <code>parameter</code> is optional. A parameter is a variable a function accepts as input inside parentheses. A function can receive zero or more parameters. If the function accepts multiple parameters, they are separated by commas. Each parameter consists of the data type followed by a name.</p>
</li>
<li><p>Inside the curly braces, <code>{}</code>, is the function’s body. Here is the actual code, the instructions that perform a specific task.</p>
</li>
<li><p>Inside the function body, there can be an optional return value. You use the <code>return</code> keyword followed by the value you want to return. If the function has a <code>voidreturn_type</code>, you don't need to specify a return value.</p>
</li>
</ul>
<h2 id="heading-how-to-call-a-function-in-c">How to Call a Function in C</h2>
<p>Here is the syntax for calling a function in C:</p>
<pre><code class="lang-c">function_name(arguments);
</code></pre>
<p>Let's break it down:</p>
<ul>
<li><p><code>function_name</code> is the name of the function you want to call. It should be the same name you used to define your function.</p>
</li>
<li><p><code>arguments</code> are the values you pass to the function. If the function accepts any parameters, you pass the arguments in parentheses when you call the function. Each argument is separated by a comma.</p>
</li>
</ul>
<p>If the function returns a value, you can store it in a variable for later use:</p>
<pre><code class="lang-c">data_type result = function_name(arguments);
</code></pre>
<h2 id="heading-how-to-define-and-call-a-function-in-c-example">How to Define and Call a Function in C Example</h2>
<p>Let's look at a simple function that adds two numbers:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> num1, <span class="hljs-keyword">int</span> num2)</span> </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">int</span> num1, num2, result;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Enter first number: "</span>);
    <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%d"</span>, &amp;num1);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Enter second number: "</span>);
    <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%d"</span>, &amp;num2);

    result = add(num1, num2);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The sum of %d and %d is %d\n"</span>, num1, num2, result);

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

<span class="hljs-comment">// Output: </span>

<span class="hljs-comment">// Enter first number: 2</span>
<span class="hljs-comment">// Enter second number: 3</span>
<span class="hljs-comment">// The sum of 2 and 3 is 5</span>
</code></pre>
<p>Let’s break down the code step by step.</p>
<h3 id="heading-include-the-header-file">Include the Header File</h3>
<p>I first included the library <code>stdio.h</code> with the line <code>#include &lt;stdio.h&gt;</code>.</p>
<p>This line includes the standard input-output library (<code>&lt;stdio.h&gt;</code>), which gives you access to the <code>printf()</code> and <code>scanf()</code> functions. Now, you can receive user input and print text to the console.</p>
<h3 id="heading-define-the-add-function">Define the <code>add</code> Function</h3>
<p>Next, I defined the following function:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> num1, <span class="hljs-keyword">int</span> num2)</span> </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}
</code></pre>
<p>This function has an <code>int</code> return type, which indicates that it will return an integer value after execution.</p>
<p>The function is named <code>add</code>, and inside parentheses, it accepts the integer parameters <code>num1</code> and <code>num2</code>.</p>
<p>Within the curly braces, the function body contains the function code. In this case, the function code consists of only the return statement <code>return num1 + num2;</code>. This code calculates the sum of <code>num1</code> and <code>num2</code> using the <code>+</code> operator, and returns the result.</p>
<p>The <code>add()</code> function is defined before being used in the <code>main()</code> function later on. In C, functions must be defined before they are used. By placing the <code>add()</code> function definition above the <code>main()</code> function, the compiler knows about it when it encounters the function call in <code>main()</code>.</p>
<h3 id="heading-define-the-main-function">Define the <code>main()</code> Function</h3>
<p>Next, I defined the <code>main()</code> function, which is the starting point of every C program:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">int</span> num1, num2, result;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Enter first number: "</span>);
    <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%d"</span>, &amp;num1);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Enter second number: "</span>);
    <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%d"</span>, &amp;num2);

    result = add(num1, num2);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The sum of %d and %d is %d\n"</span>, num1, num2, result);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Inside the <code>main()</code> function, I first declared the integer variables <code>num1</code>, <code>num2</code>, and <code>result</code>.</p>
<p>Note that <code>num1</code> and <code>num2</code> variables are different from the <code>num1</code> and <code>num2</code> parameters that the <code>add()</code> function receives. These two variables will store the numbers that the user will enter.</p>
<p>Then, I prompted the user to enter the first number using the <code>printf()</code> function, and used the <code>scanf()</code> function to read the input and store it in the variable <code>num1</code>. The <code>%d</code> format specifier is used to indicate that <code>scanf()</code> should expect an integer input.</p>
<p>I followed the exact same procedure for receiving and storing the second number.</p>
<p>Next, I called the <code>add()</code> function with the <code>num1</code> and <code>num2</code> as arguments. The <code>add()</code> function will add the two numbers together. The result of the calculation is then stored in the <code>result</code> variable.</p>
<p>Following that, I used the <code>printf()</code> function to print the <code>num1</code>, <code>num2</code> and <code>result</code> variables to the console. The format specifier <code>%d</code> is used to print integer values.</p>
<p>Lastly, the line <code>return 0;</code> is a statement that indicates that the program executed successfully. When a C program terminates, it returns an exit status to the operating system, with <code>0</code> typically indicating the program executed without any errors.</p>
<h3 id="heading-execute-the-program">Execute the Program</h3>
<p>When the program is executed, the <code>main()</code> function is called first.</p>
<p>You first see the prompt <code>Enter first number:</code>. In my case, I entered <code>2</code> as the first number.</p>
<p>Once you enter a number, you will see the second prompt: <code>Enter second number:</code>. I entered the number <code>3</code> as the second number.</p>
<p>Then, the <code>add()</code> function is called, which adds the numbers <code>2</code> and <code>3</code>.</p>
<p>Lastly, the line <code>The sum of 2 and 3 is 5</code> is printed to the console.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned the very basics of defining functions in C.</p>
<p>Specifically, you learned about the two different types of functions in C, and the general syntax for defining your own functions.</p>
<p>Lastly, you saw an example of a simple function that added two numbers and returned the result.</p>
<p>Thanks for reading, and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Arrow Functions vs Regular Functions ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, there are two main ways of writing functions. You can create functions using the regular function syntax. Or you can use the arrow function syntax. In this article, you will learn how to use both options. You'll also learn about the di... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/regular-vs-arrow-functions-javascript/</link>
                <guid isPermaLink="false">66d45de3182810487e0ce10a</guid>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Tue, 16 Jan 2024 22:19:05 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-6.53.58-PM.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, there are two main ways of writing functions. You can create functions using the regular function syntax. Or you can use the arrow function syntax.</p>
<p>In this article, you will learn how to use both options. You'll also learn about the differences between the two and when it's appropriate to use each of them.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#regular-function-syntax-vs-arrow-function-syntax">Regular Function Syntax vs Arrow Function Syntax</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-access-the-arguments-passed-to-functions">How to Access the Arguments Passed to Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#duplicate-named-parameters">Duplicate Named Parameters</a></p>
</li>
<li><p><a class="post-section-overview" href="#function-hoisting">Function Hoisting</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-handle-this-binding-in-functions">How to Handle "this" Binding in Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-use-functions-as-constructors">How to Use Functions as Constructors</a></p>
</li>
<li><p><a class="post-section-overview" href="#so-which-one-should-you-use">So Which One Should You Use?</a></p>
</li>
</ul>
<h2 id="heading-regular-function-syntax-vs-arrow-function-syntax">Regular Function Syntax vs Arrow Function Syntax</h2>
<p>To understand the difference between the two options, let's begin by looking at their syntax.</p>
<h3 id="heading-regular-function-syntax">Regular function syntax</h3>
<p>The ordinary way of declaring functions in JavaScript is to use the <code>function</code> keyword. Here is an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello '</span> + name
}
</code></pre>
<p>To return a value from a regular function, you have to explicitly use the <code>return</code> keyword. Otherwise the function will return <code>undefined</code>.</p>
<h3 id="heading-arrow-function-syntax">Arrow function syntax</h3>
<p>Arrow functions were introduced with ECMAScript 6 (ES6). They give you a more concside way of defining functions in JavaScript.</p>
<p>Using the same <code>sayHello</code> function from the previous example, let's see how to create it with the arrow function syntax.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello '</span> + name
}
</code></pre>
<p>Unlike regular functions, you don't have to use an explicit return if there's only one statement like the above example. You can write the function on a single line like so.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> <span class="hljs-string">'Hello '</span> + name
</code></pre>
<p>Note how the curly braces are also removed to implicitly return the result of the expression. You can even remove the parenthesis too if there is only one argument. See the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-function"><span class="hljs-params">name</span> =&gt;</span> <span class="hljs-string">'Hello '</span> + name
</code></pre>
<p>The <code>name</code> is the only argument the function takes. And this means you can remove the parenthesis from the argument and it will still work fine.</p>
<h2 id="heading-how-to-access-the-arguments-passed-to-functions">How to Access the Arguments Passed to Functions</h2>
<p>JavaScript provides a way to access all arguments passed to a function. But the way you acess these arguments depends on the type of function you are working with.</p>
<h3 id="heading-how-to-access-arguments-with-regular-functions">How to access arguments with regular functions</h3>
<p>You can access all the arguments passed to a regular function using the <code>arguments</code> object. The <code>arguments</code> object is an array-like object that holds all the arguments passed to the function.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logNumbers</span>(<span class="hljs-params">num1, num2</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>)
}

logNumbers(<span class="hljs-number">8</span>, <span class="hljs-number">24</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-11-at-5.01.51-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results of the arguments object</em></p>
<p>As you can see from the log result, the <code>arguments</code> object contains the two numbers passed as arguments to the <code>logNumbers</code> function.</p>
<h3 id="heading-how-to-access-arguments-with-arrow-functions">How to access arguments with arrow functions</h3>
<p>The <code>arguments</code> object is not available in arrow functions. If you try to access it in arrow functions, JavaScript will throw a reference error.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> logNumbers = <span class="hljs-function">(<span class="hljs-params">num1, num2</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>)
}

logNumbers(<span class="hljs-number">8</span>, <span class="hljs-number">24</span>) <span class="hljs-comment">// Uncaught ReferenceError: arguments is not defined</span>
</code></pre>
<p>To access the arguments passed to an arrow function, you can use the rest parameter syntax (<code>...</code>).</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> logNumbers = <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(args)
}

logNumbers(<span class="hljs-number">8</span>, <span class="hljs-number">24</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-11-at-11.13.39-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results for the arguments from an arrow function</em></p>
<p>Using the rest parameter syntax (<code>...</code>), you get access to all the arguments passed to the <code>logNumbers</code> function.</p>
<h2 id="heading-duplicate-named-parameters">Duplicate Named Parameters</h2>
<p>Another difference between regular functions and arrow functions is how they handle duplicates in the named parameters.</p>
<h3 id="heading-duplicate-named-parameters-in-regular-functions">Duplicate named parameters in regular functions</h3>
<p>When a regular function has duplicate names in the parameters, the last parameter with the duplicate name will take precedence. Let's see an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">exampleFunction</span>(<span class="hljs-params">a, b, a</span>) </span>{
  <span class="hljs-built_in">console</span>.log(a, b)
}

exampleFunction(<span class="hljs-string">"first"</span>, <span class="hljs-string">"second"</span>, <span class="hljs-string">"third"</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-9.50.00-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results for named duplicate parameters</em></p>
<p>In the example above, the <code>third</code> argument overrides the value of the <code>first</code> argument because the last duplicate parameter is the one that takes precedence.</p>
<p>But in "strict mode", using a duplicate named parameter will result in a syntax error.</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">exampleFunction</span>(<span class="hljs-params">a, b, a</span>) </span>{
  <span class="hljs-built_in">console</span>.log(a, b)
}

exampleFunction(<span class="hljs-string">"first"</span>, <span class="hljs-string">"second"</span>, <span class="hljs-string">"third"</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-10.29.11-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Strict mode doesn't allow using a parameter name more than once</em></p>
<h3 id="heading-duplicate-named-parameters-in-arrow-functions">Duplicate named parameters in arrow functions</h3>
<p>Arrow functions don't allow for the same parameter name to be used more than once in the parameter list. Doing so will result in a syntax error.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> exampleFunction = <span class="hljs-function">(<span class="hljs-params">a, b, a</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(a, b)
}

exampleFunction(<span class="hljs-string">"first"</span>, <span class="hljs-string">"second"</span>, <span class="hljs-string">"third"</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-10.29.11-AM-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Arrow functions do not allow duplicate parameter names</em></p>
<h2 id="heading-function-hoisting">Function Hoisting</h2>
<p>Hoisting in JavaScript is a behaviour where variables and functions are moved to the top of their containing scope during compilation, before the code is executed.</p>
<h3 id="heading-hosting-in-regular-functions">Hosting in regular functions</h3>
<p>Regular functions are hoisted to the top. And you can access and call them even before they are declared.</p>
<pre><code class="lang-javascript">regularFunction()

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">regularFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a regular function."</span>)
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-11.50.43-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result of calling the regular function before it's declared</em></p>
<p>The above is an example of calling a regular function before it is declared. And it works fine without throwing any error because of function hoisting.</p>
<h3 id="heading-hoisting-in-arrow-functions">Hoisting in arrow functions</h3>
<p>Arrow functions, on the other hand, cannot be accessed before they are initialised.</p>
<pre><code class="lang-javascript">arrowFunction()

<span class="hljs-keyword">const</span> arrowFunction = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is an arrow function."</span>)
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-12.07.39-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result of calling the arrow function before it's declared</em></p>
<p>Unlike regular functions, attempting to call an arrow function before it's declared will result in a reference error, as you can see from the output above.</p>
<h2 id="heading-how-to-handle-this-binding-in-functions">How to Handle <code>this</code> Binding in Functions</h2>
<p>Regular functions have their own <code>this</code> context. And this is determined dynamically depending on how you call or execute the function.</p>
<p>Arrow functions, on the other hand, do not have their own this context. Instead, they capture the <code>this</code> value from the surrounding lexical context in which the arrow function was created.</p>
<p>The following are two different scenarios using both regular functions and arrow functions. You'll see how the <code>this</code> context is determined.</p>
<h3 id="heading-1-setting-the-this-value-during-a-simple-function-call">1. Setting the <code>this</code> value during a simple function call</h3>
<p>For regular functions, a simple function call sets the <code>this</code> value to the <code>window</code> object (or to <code>undefined</code> if you're using the "strict mode"):</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myRegularFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
}

myRegularFunction()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-4.15.11-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A simple invocation of a regular function sets</em> <code>this</code> to the window object</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>

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

myFunction() <span class="hljs-comment">// udefined</span>
</code></pre>
<p>With arrow functions, a simple function call sets the <code>this</code> value to the surrounding context whether you're using strict mode or not. In the example below, the surrounding context is the global window object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myArrowFunction = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
};

myArrowFunction()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-4.15.11-PM-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A simple invocation of an arrow function sets</em> <code>this</code> to the window object</p>
<h3 id="heading-2-when-invoking-or-calling-a-method-on-an-object">2. When invoking or calling a method on an object</h3>
<p>When you invoke a method whose value is a regular function, the <code>this</code> value is set to the object on which the method is called. But when the value of the method is an arrow function, the <code>this</code> value is set to the global window object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myObject = {
  <span class="hljs-attr">regularExample</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"REGULAR: "</span>, <span class="hljs-built_in">this</span>)
  },

  <span class="hljs-attr">arrowExample</span>: <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"ARROW: "</span>, <span class="hljs-built_in">this</span>)
  }
}

myObject.regularExample()
myObject.arrowExample()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-5.46.04-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result for a method with a regular function and another with an arrow function</em></p>
<p>While the method with the regular function logs the object to the console, the one with the arrow function logs the global window object instead.</p>
<h2 id="heading-how-to-use-functions-as-constructors">How to Use Functions as Constructors</h2>
<p>For regular functions, you can create a new instance using the <code>new</code> keyword. And this sets the <code>this</code> value to the new instance you've created.</p>
<p>For arrow functions, you cannot use them as constructors. This is because the value of <code>this</code> in arrow functions is lexically scoped – that is, determined by the surrounding execution context. This behaviour does not make them suitable to be used as constructors.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">RegularFuncBird</span>(<span class="hljs-params">name, color</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name
  <span class="hljs-built_in">this</span>.species = color
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
}

<span class="hljs-keyword">const</span> ArrowFuncBird = <span class="hljs-function">(<span class="hljs-params">name, color</span>) =&gt;</span> {
  <span class="hljs-built_in">this</span>.name = name
  <span class="hljs-built_in">this</span>.color = color
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
}

<span class="hljs-keyword">new</span> RegularFuncBird(<span class="hljs-string">"Parrot"</span>, <span class="hljs-string">"blue"</span>) 
<span class="hljs-keyword">new</span> ArrowFuncBird(<span class="hljs-string">"Parrot"</span>, <span class="hljs-string">"blue"</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-5.53.17-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results for attempting to use regular and arrow functions as constructors</em></p>
<p>The <code>RegularFuncBird</code> constructor works fine with the <code>new</code> keyword, but the <code>ArrowFuncBird</code> results in a type error.</p>
<h2 id="heading-so-which-one-should-you-use">So Which One Should You Use?</h2>
<p>There is no straightforward answer to this. Whether you use a regular function or arrow function depends on the specific use case.</p>
<p>It's recommended to use regular function in any of the following cases:</p>
<ul>
<li><p>when you need to use a constructor with the <code>new</code> keyword</p>
</li>
<li><p>when you need the <code>this</code> binding to be dynamically scoped</p>
</li>
<li><p>when you want to use the <code>arguments</code> object</p>
</li>
</ul>
<p>And you can use arrow functions in any of the following cases:</p>
<ul>
<li><p>when you want a more concise syntax for the function</p>
</li>
<li><p>when you need to maintain the lexical scope of <code>this</code></p>
</li>
<li><p>for non-method functions (in most cases)</p>
</li>
</ul>
<p>As you've learned from this article, both are valid ways of defining functions in JavaScript. Remember that choosing between them is not always a matter of personal preference. Rather, it's dependent on the kind of behaviour you expect from the function.</p>
<p>Thanks for reading and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Callbacks and Higher Order Functions in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ The way functions are treated and used in JavaScript is quite interesting. They are very flexible – we can assign functions as a value to a variable, return them as a value from another function, and pass them as an argument to another function. We c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/callbacks-higher-order-functions-in-javascript/</link>
                <guid isPermaLink="false">66ba596fbca875d7790d6a90</guid>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Franklin Okolie ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jan 2024 18:07:08 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/higher-order-callbacks.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The way functions are treated and used in JavaScript is quite interesting. They are very flexible – we can assign functions as a value to a variable, return them as a value from another function, and pass them as an argument to another function. We can do all this because JavaScript treats functions as <strong>first class citizens</strong>.</p>
<p>In this article, I'll go over what higher order functions and callbacks are, and how they work in JavaScript.</p>
<h2 id="heading-functions-as-first-class-citizens-in-javascript">Functions as First Class Citizens in JavaScript</h2>
<p>Functions are defined as <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function">first class citizens</a> or first class objects in JavaScript because functions are treated like variables.</p>
<p>This means that functions in JavaScript can be:</p>
<ul>
<li>Passed as an argument to a another function.</li>
<li>Assigned as a value to a variable.</li>
<li>Returned as a value from a function.</li>
</ul>
<p>It is essential to understand how functions are treated in JavaScript, as they serve as a building block to understanding higher order and callback functions in JavaScript and how they work.</p>
<h2 id="heading-what-are-higher-order-functions">What are Higher Order Functions?</h2>
<p>Higher order functions are functions that take functions as arguments and also return a function as a value. </p>
<p>There are a lot of built-in higher order functions provided in JavaScript. We'll take a look at some and take advantage of how functions are treated as first class citizens. We'll also create our own higher order functions.</p>
<p>First, let's take a look at some examples of built-in higher order functions.</p>
<h3 id="heading-array-methods">Array Methods</h3>
<p>Array methods are usually the first introduction of higher order functions a developer will have when learning JavaScript. These include, but are not limited to, the <code>map</code>, <code>filter</code>, <code>forEach</code>, <code>find</code>, <code>findIndex</code>, <code>some</code>, and <code>every</code> array methods provided by JavaScript.  </p>
<p>These array methods or functions have a lot in common, but one of the most common feature is that they all accept a function as an argument. Below is a code snippet that demonstrates how the <code>forEach</code> array method works:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> people = [
  { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Jack"</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1988</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Kait"</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1986</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Irv"</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1970</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Lux"</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">2015</span> },
];

people.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">person</span>) </span>{
  <span class="hljs-built_in">console</span>.log(person);
});

<span class="hljs-comment">// Output:  Logs every person object in the array</span>
</code></pre>
<p>From the code sample above, we can see that the <code>forEach</code> method accepts a function as an argument which it calls on every iteration on the array. Therefore the <code>forEach</code> array method is a higher order function.</p>
<h3 id="heading-timer-events">Timer Events</h3>
<p>Another set of commonly used built-in higher order functions are the <code>setInterval</code> and <code>setTimeout</code> functions, known as timer events in JavaScript.</p>
<p>Each function accepts a function as one of its arguments and uses it to create a timed event.</p>
<p>Take a look at the code sample below to see how <code>setTimeout</code> works:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a higher order function"</span>);
}, <span class="hljs-number">1000</span>);

<span class="hljs-comment">// Output: "This is a higher order function" after 1000ms / 1 second</span>
</code></pre>
<p>The code snippet above is the most basic example of how a <code>setTimeout</code> function works. It accepts a function and a time duration in milliseconds and executes the function after the provided duration has passed. </p>
<p>From the example above, <code>This is a higher order function</code> is printed to the console after 1000 ms, or one second.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setInterval</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a higher order function"</span>);
}, <span class="hljs-number">1000</span>);

<span class="hljs-comment">// Output: "This is a higher order function" after every 1000ms / 1 second</span>
</code></pre>
<p>The <code>setInterval</code> function is similar to the <code>setTimeout</code> function, just like the array methods – although it functions differently. But we can see a common pattern: it also accepts a function as one of its parameters.</p>
<p>Unlike <code>setTimeout</code> (that executes the function after the provided duration has passed), <code>setInterval</code> executes the function over and over again every 1000ms or 1 second.</p>
<h3 id="heading-how-to-create-and-use-a-higher-order-function">How to Create and Use a Higher Order Function</h3>
<p>Higher order functions are not limited to the built-in ones provided by JavaScript.</p>
<p>Since functions in JavaScript are treated as first class objects, we can take advantage of this behavior and build highly performant and reusable functions.</p>
<p>In the examples below, we'll build a couple of functions. They'll accept the name of a customer and a greeting, and then print that info to the console.</p>
<p>First, here is a simple function that does both of those things:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params">firstName, lastName, salutation</span>) </span>{
  <span class="hljs-keyword">const</span> fullName = <span class="hljs-string">`<span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>`</span>;

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

greetCustomer(<span class="hljs-string">"Franklin"</span>, <span class="hljs-string">"Okolie"</span>, <span class="hljs-string">"Good Day"</span>);

<span class="hljs-comment">// Output: "Good Day Franklin Okolie"</span>
</code></pre>
<p><code>greetCustomer</code> accepts 3 arguments: a first name, a last name, and a salutation. Then it prints a greeting to the customer to the console.</p>
<p>But there is a problem with this function – it's doing two things: composing the full name of the customer and also printing the greeting.</p>
<p>This is not a best practice, as functions should do only one thing and do it well. So we are going to refactor our code.</p>
<p>Another function should compose the customer's name so that the <code>greetCustomer</code> function only has to print the greeting to the console. So let's write a function that handles that:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">composeName</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
  <span class="hljs-keyword">const</span> fullName = <span class="hljs-string">`<span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>`</span>;

  <span class="hljs-keyword">return</span> fullName;
}
</code></pre>
<p>Now that we have a function that combines the customer's first and last names, we can use that function in <code>greetCustomer</code>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params">composerFunc, firstName, lastName, salutation</span>) </span>{
  <span class="hljs-keyword">const</span> fullName = composerFunc(firstName, lastName);

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

greetCustomer(composeName, <span class="hljs-string">"Franklin"</span>, <span class="hljs-string">"Okolie"</span>, <span class="hljs-string">"Good Day"</span>);

<span class="hljs-comment">// Output: "Good Day Franklin Okolie"</span>
</code></pre>
<p>Now this looks cleaner, and each function does just one thing. The <code>greetCustomer</code> function now accept 4 arguments, and since one of those arguments is a function, it's now a higher order function.</p>
<p>You might have wondered earlier, how is a function being invoked inside of another function, and why?</p>
<p>Now we'll take a deep dive into function invocation and answer both of those questions.</p>
<h3 id="heading-returning-a-function-as-a-value">Returning a Function as a Value</h3>
<p>Remember that higher order functions either take a function as a parameter and/or return a function as a value.</p>
<p>Let's refactor the <code>greetCustomer</code> function to use fewer arguments and return a function:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getGreetingsDetails</span>(<span class="hljs-params">composerFunc, salutation</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
    <span class="hljs-keyword">const</span> fullName = composerFunc(firstName, lastName);

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${salutation}</span> <span class="hljs-subst">${fullName}</span>`</span>);
  };
</code></pre>
<p>The last version of <code>greetCustomer</code> accepted too many arguments. Four arguments isn't a lot, but it would still be frustrating if you messed up the order of the arguments. Generally, the fewer arguments you have, the better.</p>
<p>So in the example above, we have a function called <code>getGreetingDetails</code> which accepts <code>composerFunc</code> and <code>salutation</code> on behalf of the inner <code>greetCustomer</code> function. It then returns the inner <code>greetCustomer</code> function, which itself accepts <code>firstName</code> and <code>lastName</code> as arguments.</p>
<p>By doing this, <code>greetCustomer</code> has fewer arguments overall.</p>
<p>And with that, let's take a look at how to use the <code>getGreetingDetails</code> function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greet = getGreetingsDetails(composeName, <span class="hljs-string">"Happy New Year!"</span>);

greet(<span class="hljs-string">"Quincy"</span>, <span class="hljs-string">"Larson"</span>);

<span class="hljs-comment">// Output: "Happy New Year Quincy Larson"</span>
</code></pre>
<p>Now take a step back and admire this beautiful abstraction. Marvelous! We have used the magic of higher order functions to simplify the <code>greetCustomer</code> function.</p>
<p>Let's walk through how everything works. The higher order function named <code>getGreetingDetails</code> takes in two arguments: a function to compose the customer's first and last name, and a salutation. Then it returns a function named <code>greetCustomer</code> which accepts the first and last name of a customer as arguments.</p>
<p> The returned <code>greetCustomer</code> function also uses the argument accepted by <code>getGreetingDetails</code> to execute some actions, too.</p>
<p>At this point you're probably wondering, how can a returned function use arguments provided to a parent function? Especially given how the function execution context works. It's possible because of <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">closures</a>. Let's learn more about them now.</p>
<h3 id="heading-closures-explained">Closures Explained</h3>
<p>A closure is a function that has access to the variable in the scope where it was created even after the scope doesn't exist anymore in the execution context. This is one of the underlying mechanism of callbacks, as callbacks can still reference and use variables created in an outer function after that outer function has been closed.</p>
<p>Let's take a quick example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getTwoNumbers</span>(<span class="hljs-params">num1, num2</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> total = num1 + num2;
    <span class="hljs-built_in">console</span>.log(total);
  };
}

<span class="hljs-keyword">const</span> addNumbers = getTwoNumbers(<span class="hljs-number">5</span>, <span class="hljs-number">2</span>);

addNumbers();

<span class="hljs-comment">//Output: 7;</span>
</code></pre>
<p>The code in this example defines a function called <code>getTwoNumbers</code> and shows you how closures work. Let's explore it in more detail:</p>
<ol>
<li><code>getTwoNumbers</code> is defined as a function that takes two parameters, <code>num1</code> and <code>num2</code>.</li>
<li>Inside <code>getTwoNumbers</code>, it returns another function, which is an inner function named <code>add</code>.</li>
<li>The <code>add</code> function, when invoked, calculates the sum of <code>num1</code> and <code>num2</code> and logs the result to the console.</li>
<li>Outside the <code>getTwoNumbers</code> function, we create a variable called <code>addNumbers</code> and assign it the result of invoking <code>getTwoNumbers(5, 2)</code>. This effectively sets up a closure where <code>addNumbers</code> now "remembers" the values <code>5</code> and <code>2</code> as <code>num1</code> and <code>num2</code>.</li>
<li>Finally, we call <code>addNumbers()</code> to execute the inner <code>add</code> function. Since <code>addNumbers</code> is a closure, it still has access to the <code>num1</code> and <code>num2</code> values, which were set to <code>5</code> and <code>2</code>, respectively. It calculates their sum and logs <code>7</code> to the console.</li>
</ol>
<p>If you want to learn more about <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">closures, read more here</a>.</p>
<p>Back to our higher order function. The returned function <code>greetCustomer</code> gets returned as a value which we store in a variable named <code>greet</code>.</p>
<p>Doing that makes the <code>greet</code> variable itself a function, meaning we can invoke it as a function and pass in arguments for a first and last name.</p>
<p>And violà There you have it. These concepts can be a bit complex to grasp at first, but once you get the hang of them, they never leave you.</p>
<p>I encourage you to read through the previous sections again, play with the code in your editor, and to get the hang of how everything works together.</p>
<p>Now that you have an in-depth understanding about how higher order functions work, let's talk about callback functions.</p>
<h2 id="heading-what-are-callback-functions">What are Callback Functions?</h2>
<p>A callback function is a function that is passed into another function as an argument.</p>
<p>Again, one of the defining factors of functions as first class citizens is its ability to be passed as an argument to another function. This is called the <strong>act of passing callbacks</strong>.</p>
<p>Let go back and take a look at the timing events we discussed earlier when we were learning about the built-in functions provided in JavaScript. Here's the <code>setTimeout</code> function again:</p>
<pre><code class="lang-js"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a higher order function"</span>);
}, <span class="hljs-number">1000</span>);

<span class="hljs-comment">// Output: "This is a higher order function" after 1000ms / 1 seconds</span>
</code></pre>
<p>We've established that the <code>setTimeout</code> function is a higher order function because it accepts another function as an argument.</p>
<p>The function that's passed as an argument to the <code>setTimeout</code> function is called a callback function. This is because it is invoked or executed inside of the higher order function it's passed into.</p>
<p>To get a better understanding of callback functions, let's take another look at the <code>greetCustomer</code> function from earlier:</p>
<pre><code class="lang-js"><span class="hljs-comment">// THIS IS A CALLBACK FUNCTION</span>
<span class="hljs-comment">// IT IS PASSED AS AN ARGUMENT TO A FUNCTION</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">composeName</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
  <span class="hljs-keyword">const</span> fullName = <span class="hljs-string">`<span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>`</span>;

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

<span class="hljs-comment">// THIS IS A HIGHER ORDER FUNCTION</span>
<span class="hljs-comment">// IT ACCPEPTS A FUNCTION AS A ARGUMENT</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params">composerFunc, firstName, lastName, salutation</span>) </span>{
  <span class="hljs-keyword">const</span> fullName = composerFunc(firstName, lastName);

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

greetCustomer(composeName, <span class="hljs-string">"Franklin"</span>, <span class="hljs-string">"Okolie"</span>, <span class="hljs-string">"Good Day"</span>);

<span class="hljs-comment">// Output: "Good Day Franklin Okolie"</span>
</code></pre>
<p>The <code>composeName</code> is a callback function that is passed as an argument into the <code>greetCustomer</code> function a higher order function and it is executed inside this function.</p>
<h2 id="heading-the-difference-between-higher-order-functions-and-callback-functions">The Difference Between Higher Order Functions and Callback Functions</h2>
<p>It's important that we understand the difference between these two terms so we can communicate more clearly with teammates and during technical interviews:</p>
<ul>
<li><strong>Higher Order Function</strong>: A function that accepts a function as an argument and/or returns a function as its value.</li>
<li><strong>Callback Function</strong>: A function that's passed as a argument to another function.</li>
</ul>
<h3 id="heading-a-bag-and-book">A Bag and Book</h3>
<p>To further understand these terms, I'll share a simple analogy.</p>
<p>Imagine you have a bag and a book. You carry the book in your bag while attending a meeting, going to class, going to church, and so on.</p>
<p>In this scenario, the bag accepts your book to carry it, and also returns it when you want to use it. So the bag is like a higher order function.</p>
<p>The book is kept inside of the bag until it's ready to be used, so it's like a callback function.</p>
<h3 id="heading-fuel-and-fuel-tank">Fuel and Fuel Tank</h3>
<p>Let's take a look at another analogy; fuel and a fuel tank.</p>
<p>To fuel a car, we have to pour the fuel through the fuel tank, the fuel tank recieves the fuel – just like a higher order function.</p>
<p>The fuel is poured into the fuel tank – like a callback function.</p>
<p>I hope these analogies help to further simplify higher order and callback functions and the difference between them.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As you can see, functions in JavaScript are very flexible, and can be used in a lot of helpful ways. This flexibility also lead to two common technical terms in JavaScript, higher order functions and callback functions.</p>
<p>If you want to learn more about these topics, check out the MDN documentation on functions as <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function">first class citizens</a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function">higher order functions</a>, and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">callback functions</a>.</p>
<p>I hope you learned a lot from this article, and I hope you use your newfound knowledge to communicate your thoughts more clearly during pair coding sessions or during technical interviews.</p>
<p>For more JavaScripts tips, follow me on <a target="_blank" href="https://twitter.com/developeraspire">Twitter</a>.</p>
<p>Thanks for reading! See you next time.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write Helper Functions in React ]]>
                </title>
                <description>
                    <![CDATA[ Helper functions in React.js are like your trusty assistants, and they play a crucial role in simplifying complex tasks. When these functions are well-structured, they make your code easier to read, maintain, and reuse.  In this article, we'll explor... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/helper-functions-in-react/</link>
                <guid isPermaLink="false">66bb91b15d242388375d3886</guid>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Adeeko Tobiloba Isreal ]]>
                </dc:creator>
                <pubDate>Thu, 02 Nov 2023 20:11:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/Helper-Function-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Helper functions in React.js are like your trusty assistants, and they play a crucial role in simplifying complex tasks. When these functions are well-structured, they make your code easier to read, maintain, and reuse. </p>
<p>In this article, we'll explore the significance of helper functions in React.js projects. We'll also see how their organized use can enhance your code's clarity, make it easier to manage over time, and allow you to recycle your code for efficiency.</p>
<h3 id="heading-prerequisites">Prerequisites:</h3>
<p>Before diving into helper functions, you should have a fundamental grasp of JavaScript and React.js concepts, including components, state, and props. This knowledge will provide a solid foundation for understanding and implementing helper functions effectively.</p>
<h2 id="heading-the-role-of-helper-functions-in-reactjs">The Role of Helper Functions in React.js</h2>
<p>In this section, we'll explore the fundamental role of helper functions in React.js and why they are indispensable for efficient development. </p>
<p>We'll delve into the everyday scenarios where these functions can make complex tasks much simpler. We'll also explore how using helper functions not only improves the organization of your code but also eases the debugging process.</p>
<h3 id="heading-what-are-helper-functions">What Are Helper Functions?</h3>
<p>Helper functions are small, reusable JavaScript functions that assist your React components in performing specific tasks. They are like specialized tools that simplify your code by breaking down complex operations into manageable steps. </p>
<p>These functions are often separate from your main components and can be called whenever needed.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example of a simple helper function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotalPrice</span>(<span class="hljs-params">quantity, price</span>) </span>{
  <span class="hljs-keyword">return</span> quantity * price;
}
</code></pre>
<p>In React development, you often encounter tasks that require multiple steps or computations. Helper functions shine in these situations. </p>
<p>For instance, you might need to format dates, validate user input, or fetch data from an API. By creating helper functions for these tasks, you can write cleaner and more concise code.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example of a helper function to format a date</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formatDate</span>(<span class="hljs-params">date</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(date).toLocaleDateString();
}
</code></pre>
<h3 id="heading-benefits-of-helper-functions">Benefits of Helper Functions</h3>
<p>Using helper functions offers several advantages, such as better code organization and more straightforward debugging. </p>
<p>When your code is organized into small, focused functions, it becomes easier to understand, update, and maintain. In addition, debugging becomes less daunting because you can isolate issues to specific helper functions, making it easier to identify and fix problems.</p>
<h2 id="heading-how-to-plan-your-helper-functions">How to Plan Your Helper Functions</h2>
<p>This section will emphasize the crucial step of planning before creating helper functions in a React project. </p>
<p>We'll explore why this preparatory stage is essential and how to identify tasks that can be abstracted into these functions. You'll also see some real-world examples of scenarios where helper functions prove their worth.</p>
<h3 id="heading-the-importance-of-planning">The Importance of Planning</h3>
<p>Planning is the foundation of effective helper functions. Before creating them, you should take a moment to outline the tasks and challenges your project involves. </p>
<p>This planning process helps you anticipate the need for helper functions, ensuring that they align with your project's goals.</p>
<h3 id="heading-criteria-for-abstraction">Criteria for Abstraction</h3>
<p>To identify tasks that can be abstracted into helper functions, consider functions that are reusable, have a specific purpose, and can be logically isolated from your main components. </p>
<p>For instance, data validation, formatting, or calculations are prime candidates.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: A task like validating an email address can be abstracted into a helper function.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validateEmail</span>(<span class="hljs-params">email</span>) </span>{
  <span class="hljs-comment">// Add validation logic here</span>
  <span class="hljs-keyword">return</span> isValid;
}
</code></pre>
<h3 id="heading-when-helper-functions-are-useful">When Helper Functions are Useful</h3>
<p>Helper functions shine in situations where you need to perform similar operations in different parts of your application. </p>
<p>For example, consider a shopping cart application where you want to calculate the total price of items in multiple places. A helper function can help you do this consistently and without duplicating code.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: Calculating the total price of items in a shopping cart</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotalPrice</span>(<span class="hljs-params">cart</span>) </span>{
  <span class="hljs-keyword">let</span> totalPrice = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> item <span class="hljs-keyword">of</span> cart) {
    totalPrice += item.price * item.quantity;
  }
  <span class="hljs-keyword">return</span> totalPrice;
}
</code></pre>
<h2 id="heading-how-to-write-helper-functions">How to Write Helper Functions</h2>
<p>In this section, we'll cover the best practices for writing helper functions in a way that makes your code clean and easy to work with.</p>
<h3 id="heading-naming-conventions">Naming Conventions</h3>
<p>Choose clear and descriptive names for your helper functions. A good name should indicate what the function does. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: Naming a function that capitalizes the first letter of a string</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">capitalizeFirstLetter</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-comment">// Function logic here</span>
}
</code></pre>
<h3 id="heading-function-parameters-and-return-values">Function Parameters and Return Values</h3>
<p>Design your functions to accept necessary parameters and return meaningful values. This helps keep your functions focused and reusable.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: A function that adds two numbers</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<h3 id="heading-how-to-avoid-side-effects">How to Avoid Side Effects</h3>
<p>Try to avoid changing data outside of the function's scope. This makes your functions predictable and easier to reason about.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: A function that doesn't have side effects</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doubleArrayValues</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">const</span> doubled = arr.map(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> item * <span class="hljs-number">2</span>);
  <span class="hljs-keyword">return</span> doubled;
}
</code></pre>
<p>By following these best practices, you'll create helper functions that are easy to understand and integrate into your React project, enhancing its readability and maintainability.</p>
<h2 id="heading-how-to-manage-helper-function-dependencies">How to Manage Helper Function Dependencies</h2>
<p>In this section, we'll cover how to manage dependencies for your helper functions, including React components or external libraries.</p>
<h3 id="heading-how-to-handle-dependencies">How to Handle Dependencies</h3>
<p>When your helper functions rely on other parts of your application, like React components or external libraries, make sure to import them at the beginning of your file. This way, your helper functions have access to what they need.</p>
<p>Here's what I mean:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: Importing a React component and using it in a helper function</span>
<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">useCounter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-comment">// Function logic here</span>
}
</code></pre>
<h3 id="heading-pros-and-cons-of-dependency-management">Pros and Cons of Dependency Management</h3>
<p>There are different strategies for managing dependencies. A pro of importing dependencies at the beginning of your file is that it's clear what your helper function relies on. But a con is that it can make your code file longer if you have many dependencies. </p>
<p>Another approach is to pass dependencies as function parameters, which can make your functions more modular.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: Passing dependencies as function parameters</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useCounter</span>(<span class="hljs-params">setCountFunction</span>) </span>{
  <span class="hljs-comment">// Function logic here</span>
}
</code></pre>
<p>Choosing the right strategy depends on your project's complexity and your preference.</p>
<h2 id="heading-how-to-test-helper-functions">How to Test Helper Functions</h2>
<p>In this section, we'll highlight why testing your helper functions is crucial to ensure they function correctly. We'll also discuss popular testing tools like Jest and React Testing Library, and provide simple code examples for writing tests.</p>
<h3 id="heading-importance-of-testing">Importance of Testing</h3>
<p>Testing your helper functions is vital to make sure they do what you expect. It helps catch bugs early, prevents unexpected behavior, and provides confidence that your code works as intended, even as you make updates.</p>
<h3 id="heading-testing-tools-and-frameworks">Testing Tools and Frameworks</h3>
<p>Popular tools like Jest and React Testing Library are excellent choices for testing your React code. They provide simple and effective ways to write and run tests.</p>
<h3 id="heading-how-to-write-your-tests">How to Write Your Tests</h3>
<p>Here's a basic example of testing a helper function using Jest. In this case, we're testing the <code>addNumbers</code> function from the section on "How to Write Helper Functions":</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Import the function you want to test</span>
<span class="hljs-keyword">const</span> { addNumbers } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./your-helper-functions'</span>);

<span class="hljs-comment">// Write a test case</span>
test(<span class="hljs-string">'adds two numbers correctly'</span>, <span class="hljs-function">() =&gt;</span> {
  expect(addNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)).toBe(<span class="hljs-number">5</span>); <span class="hljs-comment">// Check if the function returns the expected result</span>
});
</code></pre>
<p>Writing tests like this allows you to confirm that your helper functions work correctly and continue to do so as your project evolves.</p>
<h2 id="heading-documentation-and-comments">Documentation and Comments</h2>
<p>In this section, you'll learn why of clear and comprehensive documentation is important for helper functions. I'll also explain how it benefits developers and future maintainers. Then we'll look at some guidelines for writing effective comments and documentation.</p>
<h3 id="heading-significance-of-documentation">Significance of Documentation</h3>
<p>Documentation is essential because it helps developers understand how to use your helper functions. Well-documented code serves as a guide, reducing the learning curve for new developers and ensuring that existing developers don't forget how the functions work over time.</p>
<p>Clear documentation benefits developers by providing insights into what a helper function does, what parameters it expects, and what it returns. This leads to faster development, fewer errors, and more maintainable code. </p>
<p>For future maintainers, comprehensive documentation is invaluable for understanding and updating code without breaking existing functionality.</p>
<h3 id="heading-guidelines-for-comments-and-documentation">Guidelines for Comments and Documentation</h3>
<p>Here are some simple guidelines for writing comments and documentation:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/**
 * A helper function that calculates the total price.
 *
 * <span class="hljs-doctag">@param <span class="hljs-type">{number[]}</span> <span class="hljs-variable">prices</span></span> - An array of item prices.
 * <span class="hljs-doctag">@returns <span class="hljs-type">{number}</span> </span>The total price of all items.
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotalPrice</span>(<span class="hljs-params">prices</span>) </span>{
  <span class="hljs-keyword">return</span> prices.reduce(<span class="hljs-function">(<span class="hljs-params">acc, price</span>) =&gt;</span> acc + price, <span class="hljs-number">0</span>);
}
</code></pre>
<h2 id="heading-how-to-organize-helper-functions">How to Organize Helper Functions</h2>
<p>In this section, we'll discuss strategies for effectively organizing your helper functions within your React project. Proper organization makes your codebase more manageable as it scales.</p>
<h3 id="heading-strategies-for-organization">Strategies for Organization</h3>
<p>Organizing your helper functions is crucial to keep your project clean and maintainable. </p>
<p>Consider creating a dedicated directory for your helper functions. You can structure it based on functionality, where related functions are grouped together.</p>
<pre><code class="lang-plaintext">src/
|-- components/
|-- helperFunctions/
   |-- dataManipulation/
      |-- formatDate.js
      |-- calculateTotalPrice.js
   |-- validation/
      |-- validateEmail.js
      |-- validatePassword.js
</code></pre>
<p>For smaller projects, you may opt for utility files that contain multiple helper functions in one file. But as your project grows, organizing them into separate files within directories becomes more efficient.</p>
<h3 id="heading-naming-conventions-1">Naming Conventions</h3>
<p>Follow clear and consistent naming conventions for your directories and files. This makes it easy for you and other developers to locate specific helper functions. </p>
<p>For instance, use descriptive names like <code>dataManipulation</code> or <code>validation</code> for directories and camelCase for file names.</p>
<h2 id="heading-reusability-and-sharing">Reusability and Sharing</h2>
<p>In this section, we'll delve into the concept of reusability in helper functions and how to make them available for broader use.</p>
<h3 id="heading-reusability-in-helper-functions">Reusability in Helper Functions</h3>
<p>Reusability is a key concept in helper functions. These functions are designed to be reused in multiple parts of your project. By writing functions that perform specific, commonly needed tasks, you can avoid duplicating code and simplify maintenance.</p>
<h3 id="heading-how-to-make-helper-functions-available-internally">How to Make Helper Functions Available Internally</h3>
<p>To use helper functions in multiple parts of your project, simply import them as needed. </p>
<p>For instance, if you have a utility file with helper functions, import those functions into various components or modules where they are required.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { formatDate, calculateTotalPrice } <span class="hljs-keyword">from</span> <span class="hljs-string">'./helperFunctions'</span>;
</code></pre>
<h3 id="heading-how-to-share-helper-functions-externally">How to Share Helper Functions Externally</h3>
<p>If you want to share your helper functions with others or use them in different projects, you can package them as an npm module or publish them on a code-sharing platform like GitHub. This way, they become accessible to the open-source community and can be easily integrated into various projects.</p>
<p>By focusing on reusability and sharing, you maximize the value of your helper functions, making them available for use in multiple parts of your project and beyond. This promotes code efficiency and collaboration with others in the</p>
<h2 id="heading-performance-considerations">Performance Considerations</h2>
<p>In this section, we'll discuss essential performance considerations when working with helper functions.</p>
<h3 id="heading-how-to-write-efficient-helper-functions">How to Write Efficient Helper Functions</h3>
<p>When writing helper functions, consider potential performance bottlenecks. In situations where your functions are called frequently or work with large datasets, inefficient code can slow down your application. Optimize algorithms and data structures to improve performance.</p>
<h3 id="heading-profiling-and-measuring">Profiling and Measuring</h3>
<p>Profiling and measuring are essential techniques to ensure that your helper functions and overall codebase perform optimally. </p>
<p>Profiling helps you analyze how different parts of your code consume resources, allowing you to pinpoint performance bottlenecks and focus your optimization efforts where they are needed most. Measuring involves quantifying the time taken by specific operations.</p>
<p>Here's a simplified explanation and a basic example of how you can profile your code using the Chrome DevTools performance tab:</p>
<ol>
<li>Open Chrome DevTools by right-clicking on your web page and selecting "Inspect."</li>
<li>Go to the "Performance" tab.</li>
<li>Start recording the performance by clicking the record button.</li>
<li>Interact with your application and perform the actions you want to profile.</li>
<li>Stop recording.</li>
<li>Review the performance analysis report to identify bottlenecks and areas that need optimization.</li>
</ol>
<p>Check out this link below for more on using chrome dev tools for analysis:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.thisdot.co/blog/performance-analysis-with-chrome-devtools/">https://www.thisdot.co/blog/performance-analysis-with-chrome-devtools/</a></div>
<p>You can identify the performance bottlenecks, such as functions consuming excessive CPU or causing re-renders.</p>
<p>Common profiling and measuring tools include:</p>
<ol>
<li><strong>Chrome DevTools:</strong> Built into Google Chrome, DevTools provides detailed insights into JavaScript and rendering performance.</li>
<li><strong>React DevTools:</strong> A browser extension for profiling React applications specifically.</li>
<li><strong>Lighthouse:</strong> An open-source tool for auditing web page performance and generating performance reports.</li>
<li><strong>Webpack Bundle Analyzer:</strong> For visualizing the size and composition of your application bundles.</li>
<li><strong>Jest and React Testing Library:</strong> These testing tools can measure the performance of your unit and integration tests.</li>
</ol>
<p>These tools help you dig deeper into your code's performance and identify areas where optimization can yield the most significant benefits.</p>
<h3 id="heading-the-importance-of-optimization">The Importance of Optimization</h3>
<p>Efficient helper functions not only improve performance but also enhance the overall user experience. In a React project, fast and responsive applications are crucial. </p>
<p>Optimizing data and algorithms is crucial for improving the efficiency and performance of your applications. The best approach involves a number of key strategies:</p>
<ul>
<li><strong>Analyze and Profile:</strong> Begin by measuring and profiling your code to identify performance bottlenecks. Tools like Chrome DevTools can help you pinpoint areas that need optimization.</li>
<li><strong>Select Efficient Data Structures:</strong> Choose the right data structures for your specific use case. For example, use maps for fast key-based access or arrays for indexed data.</li>
<li><strong>Algorithms Matter:</strong> Ensure that the algorithms you use are well-suited to the problem you're solving. Sometimes, a more efficient algorithm can drastically improve performance.</li>
<li><strong>Minimize Unnecessary Work:</strong> Avoid redundant calculations or unnecessary data processing. Cache results when appropriate to prevent recomputation.</li>
<li><strong>Batch Operations:</strong> Instead of processing items one by one, consider batch operations. For example, use the <code>map</code> function instead of a <code>for</code> loop for operations on arrays.</li>
<li><strong>Lazy Loading:</strong> Load data and perform computations only when they are needed, rather than preloading everything upfront.</li>
<li><strong>Use Memoization:</strong> Implement memoization for expensive function calls. This technique stores previously computed results and returns them if the same input is encountered again.</li>
<li><strong>Minimize Re-renders:</strong> In a React project, optimize component rendering to reduce unnecessary re-renders. Use React's <code>memo</code> or <code>PureComponent</code> to prevent re-renders when props and state haven't changed.</li>
<li><strong>Asynchronous Operations:</strong> Move time-consuming operations to web workers or use asynchronous processing to prevent blocking the main thread.</li>
<li><strong>Testing and Benchmarking:</strong> Continuously test and benchmark your code to ensure that optimizations don't introduce new issues or regressions.</li>
<li><strong>Prioritize Based on Impact:</strong> Focus your optimization efforts on the most critical and frequently used parts of your application. Don't spend excessive time optimizing code with minimal impact on performance.</li>
<li><strong>Documentation and Comments:</strong> Document your optimization efforts, including reasons and changes made, to help other developers understand and maintain the code.</li>
</ul>
<p>Optimizing data and algorithms is an ongoing process that requires a balance between readability and performance. Regularly measuring and profiling your code, along with following best practices, will help you achieve optimal performance without sacrificing maintainability and readability.</p>
<p>By addressing performance considerations, you ensure that your helper functions do their job effectively without negatively impacting the user's interaction with your app.</p>
<p>Addressing performance considerations and optimizing your helper functions are essential steps to deliver a high-quality user experience and maintain the responsiveness of your React project.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Well-structured and well-documented helper functions are the unsung heroes of efficient React.js development. They simplify complex tasks, enhance code readability, and promote maintainability. </p>
<p>By following best practices, including clear documentation, organized organization, and thoughtful testing, you not only make your code easier to work with but also improve your development workflow. </p>
<p>Embrace the power of helper functions in your React.js projects, and you'll discover how these small yet mighty tools can make your coding life easier and more enjoyable while delivering robust and performant applications.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ strcmp in C – How to Compare Strings in C ]]>
                </title>
                <description>
                    <![CDATA[ Comparing strings is a common task in most programming languages. In C, you can use the strcmp function to handle string comparisons.  In this article, I will show you practical examples of the strcmp function, and offer insights into how it compares... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/strcmp-in-c-how-to-compare-strings-in-c/</link>
                <guid isPermaLink="false">66b90310380c84d101de5db3</guid>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Md. Fahim Bin Amin ]]>
                </dc:creator>
                <pubDate>Thu, 27 Apr 2023 20:32:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/max-duzij-qAjJk-un3BI-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Comparing strings is a common task in most programming languages. In C, you can use the <code>strcmp</code> function to handle string comparisons. </p>
<p>In this article, I will show you practical examples of the <code>strcmp</code> function, and offer insights into how it compares strings, what its return values mean, and how to use it effectively. </p>
<p>You'll also see some best practices to help optimize your code.</p>
<h2 id="heading-what-are-strings-in-c">What are Strings in C?</h2>
<p>Before we discuss the <code>strcmp</code> function, it is important to understand the basics of strings in C. </p>
<p>A string is an array of characters terminated by a null character ('\0').<br>Strings are usually represented either using character pointers ( <code>char *</code> ) or character arrays ( <code>char []</code> ).</p>
<h2 id="heading-what-is-the-strcmp-function-of-c-and-how-does-it-work">What is t<strong>he <code>strcmp()</code> function of C, and how does it work?</strong></h2>
<p>The <code>strcmp()</code> function is part of the standard C library ( <code>string.h</code> ). Its primary purpose is to compare the characters of the two strings in sequence until it finds a mismatch or until the end of the strings is reached (that is, the null character '\0'). In our programming world, we call it <a target="_blank" href="https://en.wikipedia.org/wiki/Lexicographic_order">lexicographic order</a>-based searching.</p>
<p>The function prototype for <code>strcmp</code> is as follows:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">strcmp</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span> *s1, <span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span> *s2)</span></span>;
</code></pre>
<p>Here's what the parameters above mean:</p>
<ul>
<li><strong>s1</strong> denotes the first string to be compared.</li>
<li><strong>s2</strong> denotes the second string to be compared.</li>
</ul>
<p><code>strcmp()</code> is like a game that compares two words. It helps us to identify whether a word comes before or after another word in the dictionary.</p>
<ul>
<li>If the first word (<strong>s1</strong>) comes before the second word (<strong>s2</strong>) in the dictionary, <code>strcmp()</code> gives a negative number.</li>
<li>If the first word (<strong>s1</strong>) comes after the second (<strong>s2</strong>) word in the dictionary, <code>strcmp()</code> gives a positive number.</li>
<li>If both words are the same, <code>strcmp()</code> gives the number 0.</li>
</ul>
<p><code>strcmp()</code> compares the corresponding characters from both strings based on their ASCII values, which are numeric codes that represent each character.</p>
<p>Therefore, if the ASCII value of the first differing character in the first string is less than the ASCII value of the corresponding character in the second string, <code>strcmp()</code> returns a negative number. This indicates that the first string comes before the second string in the dictionary. </p>
<p>If the ASCII value of the first differing character in the first string is greater than the ASCII value of the corresponding character in the second string, <code>strcmp()</code> returns a positive number. This indicates that the first string comes after the second string in the dictionary.</p>
<p>If the two strings are equal up to the end of the shorter string, <code>strcmp()</code> returns a negative, zero, or positive value depending on whether the longer string has a character with a smaller, equal, or greater ASCII value than the null character.</p>
<p>Actually, the C compiler implements this logic of comparing the ASCII values of characters in two strings and returning the result accordingly.</p>
<h2 id="heading-strcmp-function-example-1-basic-string-comparison"><code>strcmp()</code> Function Example #1 – Basic String Comparison</h2>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;string.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">char</span> str1[] = <span class="hljs-string">"apple"</span>;
    <span class="hljs-keyword">char</span> str2[] = <span class="hljs-string">"banana"</span>;

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

    <span class="hljs-keyword">if</span> (result == <span class="hljs-number">0</span>) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The strings are equal.\n"</span>);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (result &lt; <span class="hljs-number">0</span>) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"String 1 is less than string 2.\n"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"String 1 is greater than string 2.\n"</span>);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<pre><code><span class="hljs-built_in">String</span> <span class="hljs-number">1</span> is less than string <span class="hljs-number">2.</span>
</code></pre><p>Let me now explain each of the lines from the code given above.</p>
<p>Here, I have taken two different strings as two different character arrays, as we do not have access to direct strings in the <strong>C</strong> programming language. </p>
<p>In the first character string ( <code>str1[]</code> ), I have stored the string <code>apple</code>. In the second character string ( <code>str2[]</code> ), I have stored the string <code>banana</code>. As the function <code>strcmp()</code> gives a boolean output (true/false, or 0/1), I have taken another int variable named <code>result</code> to store the boolean value ( <code>1</code> for <code>true</code> and <code>0</code> for <code>false</code>).</p>
<p>The <code>strcmp()</code> function compares the two strings, and finds out that the first string <code>apple</code> comes before the second string <code>banana</code>. Therefore, the function <code>strcmp()</code> returns a negative value indicating that the first string is less than the second string. </p>
<p>Based on the value in <code>result</code>, it prints <code>String 1 is less than string 2.</code>.</p>
<p>If you are confused about "the string comes before or after another string" then let me explain to you a bit more.</p>
<p>When we say that the first string comes before the second string, we mean that if the two strings were listed in a dictionary or a sorted list of words, the first string would appear before the second string.</p>
<p>In the case of the program above, the first string is <code>"apple"</code>, and the second string is <code>"banana"</code>. If we were to look up these two words in a dictionary, we would find that <code>"apple"</code> appears before <code>"banana"</code>, which means that the first string comes before the second string.</p>
<p>The <code>strcmp()</code> function compares the two strings character by character and determines which string comes first in the dictionary based on the ASCII values of the characters. </p>
<p>In this case, the first character of <code>"apple"</code> (which is <code>'a'</code>) has a lower ASCII value (ASCII value for a = 97) than the first character of <code>"banana"</code> (which is <code>'b'</code> and the ASCII value for b = 98), so <code>strcmp()</code> returns a negative value, indicating that the first string comes before the second string.</p>
<p>I hope this clears up any confusion regarding what the phrase "one string comes after/before another string" means.</p>
<h2 id="heading-strcmp-function-example-2-case-insensitive-string-comparison"><code>strcmp()</code> Function Example #2 – Case-insensitive String Comparison</h2>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;string.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">char</span> str1[] = <span class="hljs-string">"Apple"</span>;
    <span class="hljs-keyword">char</span> str2[] = <span class="hljs-string">"apple"</span>;

    <span class="hljs-comment">// Convert both strings to lowercase</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; str1[i]; i++) {
        str1[i] = <span class="hljs-built_in">tolower</span>(str1[i]);
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; str2[i]; i++) {
        str2[i] = <span class="hljs-built_in">tolower</span>(str2[i]);
    }

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

    <span class="hljs-keyword">if</span> (result == <span class="hljs-number">0</span>) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The strings are equal.\n"</span>);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (result &lt; <span class="hljs-number">0</span>) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"String 1 is less than string 2.\n"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"String 1 is greater than string 2.\n"</span>);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<pre><code>The strings are equal.
</code></pre><p>Here I converted both strings into lowercase. I used a for loop to change all the characters in the string to lowercase using the function <code>tolower()</code>. The <code>for</code> loops convert both strings to lowercase by iterating over each character of the strings using an index variable <code>i</code>, and calling the <code>tolower()</code> function on each character to convert it to lowercase.</p>
<p>After converting both strings into lowercase, I called the function <code>strcmp()</code> to check whether both strings are equal or not, like earlier. I stored the output of the <code>strcmp()</code> function in a new variable named <code>result</code>, like earlier.</p>
<p>The <code>if</code> statement checks the value of <code>result</code> and prints out the corresponding message depending on whether the strings are equal, or which string is less or greater. Here, the two strings become equal after converting them to lowercase. Thus, the first <code>if</code> statement executes and provides the output.</p>
<p>Keep in mind that, after converting both strings to lowercase, the value of <code>str1</code> is <code>"apple"</code>, which is the same as the value of <code>str2</code> in the ASCII.</p>
<p>Therefore, when the <code>strcmp()</code> function is called, it returns <code>0</code>, which indicates that the strings are equal. This can be useful when we want to compare strings that may differ in case but should be considered equal.</p>
<h2 id="heading-strcmp-best-practices"><code>strcmp()</code> Best Practices</h2>
<p>Here are some best practices to follow when using the <code>strcmp()</code> function:</p>
<ul>
<li>Always include the <code>string.h</code> header when using <code>strcmp()</code>.</li>
<li>To compare case-insensitive strings, use a custom function like <code>strcasecmp()</code> or a standard library function like <code>stricmp()</code>.</li>
<li>Be cautious when comparing strings that may contain non-ASCII characters, as <code>strcmp()</code> uses the difference in ASCII values for comparisons, which might not work as expected for non-ASCII characters. In such cases, consider using a Unicode-aware comparison function or library. </li>
</ul>
<p>If you want to learn more about ASCII characters, check out <a target="_blank" href="https://www.freecodecamp.org/news/ascii-table-hex-to-ascii-value-character-code-chart-2/">this article</a>.</p>
<h2 id="heading-alternative-string-comparison-functions">Alternative String Comparison Functions</h2>
<p>Apart from <code>strcmp()</code>, there are other string comparison functions available in the C standard library:</p>
<ul>
<li><code>strncmp()</code>: Compares up to a specified number of characters of two strings. It is useful when you want to compare only a portion of the strings.</li>
<li><code>strcoll()</code>: This is quite interesting. Let me explain more about this.</li>
</ul>
<p>The <code>strcoll()</code> function is like a game that helps us compare two words or strings, just like <code>strcmp()</code>. But <code>strcoll()</code> is designed to handle strings that contain non-ASCII characters or require language-specific comparisons, such as words from different languages.</p>
<p><code>strcoll()</code> uses the rules for comparing words that are specific to the language or region, based on the current locale setting of the computer. In other words, it compares words according to the language-specific collation rules of the locale, which may be different from the standard ASCII ordering used by <code>strcmp()</code>.</p>
<p>For example, in the Spanish language, the word "cañón" (which means "canyon" in English) is sorted after "casa" (which means "house" in English), because the letter "ñ" is considered a separate letter in the Spanish alphabet, and comes after "n".</p>
<p>So, <code>strcoll()</code> can be useful for comparing words from different languages or regions that have specific collation rules, and we use this function for this kind of specific need.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we've explored the <code>strcmp()</code> function in C, how it compares strings, and its return values. We've also looked at examples and best practices for using <code>strcmp</code> effectively. </p>
<p>With this knowledge, you can easily compare strings in C like a pro. Remember to consider alternative comparison functions like <code>strncmp()</code> and <code>strcoll()</code> when working with specific use cases, such as partial or locale-specific string comparisons.</p>
<p>If this article helps you in any way, then let me know via <a target="_blank" href="https://twitter.com/Fahim_FBA">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/fahimfba/">LinkedIn</a>. You can also follow me on <a target="_blank" href="https://github.com/FahimFBA">GitHub</a> and check my <a target="_blank" href="https://www.youtube.com/@FahimAmin?sub_confirmation=1">YouTube channel</a>, and <a target="_blank" href="https://fahimbinamin.com/">my website</a>. You can also <a target="_blank" href="https://www.buymeacoffee.com/fahimbinamin">buy me a coffee</a> if you want to support me.</p>
<p>Cover: Photo by <a target="_blank" href="https://unsplash.com/@max_duz?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Max Duzij</a> on <a target="_blank" href="https://unsplash.com/s/photos/programming?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Functions in C - Explained With Examples ]]>
                </title>
                <description>
                    <![CDATA[ Functions are an essential component of the C programming language. They help you divide bigger problems into smaller, more manageable chunks of code, making it simpler to create and run programs.  We'll look at functions in C, their syntax, and how ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-functions-in-c/</link>
                <guid isPermaLink="false">66ba611f739c8c931a5408ad</guid>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ valentine Gatwiri ]]>
                </dc:creator>
                <pubDate>Thu, 06 Apr 2023 14:20:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/guillaume-bolduc-uBe2mknURG4-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Functions are an essential component of the C programming language. They help you divide bigger problems into smaller, more manageable chunks of code, making it simpler to create and run programs. </p>
<p>We'll look at functions in C, their syntax, and how to use them successfully in this article.</p>
<h2 id="heading-what-is-a-function-in-c">What is a Function in C?</h2>
<p>A function is a block of code that executes a particular task in programing. It is a standalone piece of code that can be called from anywhere in the program. </p>
<p>A function can take in parameters, run computations, and output a value. A function in C can be created using this syntax:</p>
<pre><code class="lang-c"><span class="hljs-function">return_type <span class="hljs-title">function_name</span><span class="hljs-params">(parameter <span class="hljs-built_in">list</span>)</span> </span>{
   <span class="hljs-comment">// function body</span>
}
</code></pre>
<p>The <code>return_type</code> specifies the type of value that the function will return. If the function does not return anything, the <code>return_type</code> will be <code>void</code>. </p>
<p>The <code>function_name</code> is the name of the function, and the <code>parameter list</code> specifies the parameters that the function will take in.</p>
<h2 id="heading-how-to-declare-a-function-in-c">How to Declare a Function in C</h2>
<p>Declaring a function in C informs the compiler about the presence of a function without giving implementation details. This enables the function to be called by other sections of the software before it is specified or implemented.</p>
<p>A function declaration usually contains the <code>function name</code>, <code>return type</code>, and the parameter types. The following is the syntax for defining a function in C:</p>
<pre><code class="lang-c"><span class="hljs-function">return_type <span class="hljs-title">function_name</span><span class="hljs-params">(parameter_list)</span></span>;
</code></pre>
<p>Here, <code>return_type</code> is the data type of the value that the function returns. <code>function_name</code> is the name of the function, and <code>parameter_list</code> is the list of parameters that the function takes as input.</p>
<p>For example, suppose we have a function called <code>add</code> that takes two integers as input and returns their sum. We can declare the function as follows:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> num1, <span class="hljs-keyword">int</span> num2)</span></span>;
</code></pre>
<p>This tells the compiler that there is a function called <code>add</code> that takes two integers as input and returns an integer as output.</p>
<p>It's worth noting that function declarations do not include the function body, which includes the actual code that runs when the function is invoked. </p>
<p>The body of the function is defined independently of the function statement, usually in a separate block of code called the function definition.</p>
<p>Here's an example:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-comment">/* function statement */</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span></span>;

<span class="hljs-comment">/* function definition */</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
    <span class="hljs-keyword">return</span> a + b;
}

<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> result = add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The result is %d\n"</span>, result);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>In this example, the <code>add</code> function is declared with a function statement at the top of the file, which specifies its name, return type (<code>int</code>), and parameters (<code>a</code> and <code>b</code>, both <code>int</code>s).</p>
<p>The actual code for the <code>add</code> function is defined in the function definition. Here, the function simply adds its two parameters and returns the result.</p>
<p>The <code>main</code> function calls the <code>add</code> function with arguments <code>2</code> and <code>3</code>, and stores the result in the <code>result</code> variable. Finally, it prints the result using the <code>printf</code> function.</p>
<h3 id="heading-how-to-use-a-function-in-multiple-source-files">How to Use a Function in Multiple Source Files</h3>
<p>If you want to use a function in numerous source files, you must include a function declaration (also known as a function prototype) in the header file and the definition in one source file.</p>
<p>when you build, you first compile the source files to object files, and then you link the object files into the final executable.</p>
<p>Let's create a header file called <code>myfunctions.h</code>:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">ifndef</span> MYFUNCTIONS_H</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> MYFUNCTIONS_H</span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span></span>;<span class="hljs-comment">// Function prototype, its declaration</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span> <span class="hljs-comment">/* MYFUNCTIONS_H */</span></span>
</code></pre>
<p>In this header file, we declare a function <code>add</code> using a function statement.</p>
<p>Next, let's create a source file called <code>myfunctions.c</code>, which defines the <code>add</code> function:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"myfunctions.h"</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
    <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>In this file, we include the <code>myfunctions.h</code> header file using quotes, and we define the <code>add</code> function.</p>
<p>Finally, let's create a source file called <code>main.c</code>, which uses the <code>add</code> function:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"myfunctions.h"</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> a = <span class="hljs-number">10</span>, b = <span class="hljs-number">5</span>;
    <span class="hljs-keyword">int</span> sum = add(a, b);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Sum of %d and %d is %d\n"</span>, a, b, sum);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>In this file, we include both the <code>stdio.h</code> header file and our <code>myfunctions.h</code> header file using angle brackets and quotes, respectively. We then call the <code>add</code> function, passing in values <code>a</code> and <code>b</code> and storing the result in <code>sum</code>. Finally, we print the result using <code>printf</code>.</p>
<p> The way you create it is heavily influenced by your environment. If you are using an IDE (such as Visual Studio), you must position all files in the proper locations in the project.</p>
<p>If you are creating from the command line e.g Linux. To compile this program, you would need to compile both <code>myfunctions.c</code> and <code>main.c</code> and link them together as shown below:</p>
<pre><code>gcc -c myfunctions.c
gcc -c main.c
gcc -o program main.o myfunctions.o
</code></pre><p>The <code>-c</code> option instructs the compiler to create an object file with the same name as the source file but with a <code>.o</code> suffix. The final instruction joins the two object files to create the final executable, which is named <code>program</code> (the -o option specifies the name of the output file).</p>
<h2 id="heading-what-happens-if-you-call-a-function-before-its-declaration-in-c">What Happens if You Call a Function Before Its Declaration in C?</h2>
<p>In this instance, the computer believes the usual return type is an integer. If the function gives a different data type, it throws an error. </p>
<p>If the return type is also an integer, it will function properly. But some cautions may be generated:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
main() {
   <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The returned value: %d"</span>, function);
}
<span class="hljs-function"><span class="hljs-keyword">char</span> <span class="hljs-title">function</span><span class="hljs-params">()</span> </span>{
   <span class="hljs-keyword">return</span> <span class="hljs-string">'V'</span>;
}
</code></pre>
<p>In this code, the function <code>function()</code> is  called before it is declared. This returns an error:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-from-2023-04-05-14-03-36.png" alt="Image" width="600" height="400" loading="lazy">
<em>warnings and errors</em></p>
<h2 id="heading-how-to-define-a-function-in-c">How to Define a Function in C</h2>
<p>Assuming you want to create a code that accepts two integers and returns their sum, you can define a function that does that this way:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">sum</span><span class="hljs-params">(<span class="hljs-keyword">int</span> num1, <span class="hljs-keyword">int</span> num2)</span> </span>{
   <span class="hljs-keyword">int</span> result = num1 + num2;
   <span class="hljs-keyword">return</span> result;
}
</code></pre>
<p>In this example, the function <code>sum</code> takes in two integer parameters – <code>num1</code> and <code>num2</code>. The function calculates their sum and returns the result. The return type of the function is <code>int</code>.</p>
<h2 id="heading-where-should-a-function-be-defined">Where Should a Function Be Defined?</h2>
<p>In C, a function can be defined anywhere in the program, as long as it is defined before it is used. But it is a good practice to define functions at the beginning of the file or in a separate file to make the code more readable and organized.</p>
<p>Here's an example code showing how to define a function in C:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-comment">// function declaration (also known as function prototype)</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
   <span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>, y = <span class="hljs-number">20</span>, sum;
   sum = add(x, y);
   <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The sum of %d and %d is %d\n"</span>, x, y, sum);
   <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}

<span class="hljs-comment">// function definition</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
   <span class="hljs-keyword">int</span> result;
   result = a + b;
   <span class="hljs-keyword">return</span> result;
}
</code></pre>
<p>In this example, the function <code>add()</code> is defined after its declaration (or prototype) within the same file.</p>
<p>Another approach is to define the function in a separate header file, which is then included in the main file using the <code>#include</code> directive. For example:</p>
<pre><code class="lang-c"><span class="hljs-comment">// header file: math.h</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">ifndef</span> MATH_H</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> MATH_H</span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span></span>;

<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span>
</code></pre>
<pre><code class="lang-c"><span class="hljs-comment">// main file: main.c</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"math.h"</span>  <span class="hljs-comment">// include the header file</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
   <span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>, y = <span class="hljs-number">20</span>, sum;
   sum = add(x, y);
   <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The sum of %d and %d is %d\n"</span>, x, y, sum);
   <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<pre><code class="lang-c"><span class="hljs-comment">// implementation file: math.c</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
   <span class="hljs-keyword">int</span> result;
   result = a + b;
   <span class="hljs-keyword">return</span> result;
}
</code></pre>
<p>In this approach, the function declaration (or prototype) is included in the header file <code>math.h</code>, which is then included in the main file <code>main.c</code> using the <code>#include</code> directive. The function implementation is defined in a separate file <code>math.c</code>.</p>
<p>This approach allows for better code organization and modularity, as the function implementation can be separated from the main program code.</p>
<h3 id="heading-how-to-call-a-function-in-c">How to Call a Function in C</h3>
<p>We can call a function from anywhere in the program once we've defined it. We use the function name followed by the argument list in parentheses to call a function. For example, we can use the following code to call the <code>sum</code> function that we defined earlier:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> a = <span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> b = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> c = sum(a, b);
</code></pre>
<p>In this code, we are calling the <code>sum</code> function with <code>a</code> and <code>b</code> as its parameters. The function returns the sum of <code>a</code> and <code>b</code>, which is then stored in the variable <code>c</code>.</p>
<h2 id="heading-how-to-pass-parameters-to-a-function">How to Pass Parameters to a Function</h2>
<p>There are two methods of passing parameters (also called arguments) to a function in C: by value and by reference. </p>
<p>When we pass a parameter by value, the method receives a copy of the parameter's value. Changes to the parameter within the code have no effect on the initial variable outside the function. </p>
<p>When we pass a parameter by reference, the method receives a link to the parameter's memory location. Any modifications to the parameter within the code will have an impact on the initial variable outside the function.</p>
<p>Consider the following examples of passing parameters by value and by reference. Assuming we want to create a function that accepts an integer and multiplies it by two, the function can be defined as follows:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doubleValue</span><span class="hljs-params">(<span class="hljs-keyword">int</span> num)</span> </span>{
   num = num * <span class="hljs-number">2</span>;
}
</code></pre>
<p>In this example, the function <code>doubleValue</code> takes in an integer parameter <code>num</code> by value. It doubles the value of <code>num</code> and assigns it back to <code>num</code>. However, this change will not affect the original value of <code>num</code> outside the function.</p>
<p>Here's another example that shows how you can pass a single parameter by value:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">square</span><span class="hljs-params">(<span class="hljs-keyword">int</span> num)</span> </span>{
    <span class="hljs-comment">// Function to calculate the square of a number.</span>
    <span class="hljs-keyword">int</span> result = num * num;
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d\n"</span>, result);
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    square(<span class="hljs-number">5</span>);  <span class="hljs-comment">// Output: 25</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>In this example, we define a function called <code>square</code> that takes an integer parameter <code>num</code> by value. Inside the function, we calculate the square of <code>num</code> and print the result. We then call the function with the argument <code>5</code>.</p>
<p>Now, let's look at an example of passing a parameter by reference:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">square</span><span class="hljs-params">(<span class="hljs-keyword">int</span>* num)</span> </span>{
    <span class="hljs-comment">// Function to calculate the square of a number.</span>
    *num = (*num) * (*num);
}

<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> x = <span class="hljs-number">5</span>;
    square(&amp;x);
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d\n"</span>, x);  <span class="hljs-comment">// Output: 25</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>In this example, we define a function <code>square</code> that takes an integer pointer parameter <code>num</code> by reference. Inside the function, we reference the pointer and calculate the square of the value pointed to by <code>num</code>. </p>
<p>We then call the function with the address of the integer variable <code>x</code>. After calling the function, the value of <code>x</code> is modified to be the square of its original value, which we then print in the <code>main</code> function.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, functions are an essential component of C programming. You can use them to divide large problems into smaller, more manageable pieces of code.</p>
<p>You can declare and define functions in C, and pass parameters either by value or by reference. It's a good practice to declare all functions before using them, and to define them at the beginning of the file or in a separate file for better code organization and modularity. </p>
<p>By using functions effectively, you can write cleaner, more readable code that is easier to debug and maintain.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Nested Functions in Google Sheets ]]>
                </title>
                <description>
                    <![CDATA[ Data analysis is an extremely valuable skill to have. But to make the most of your analysis, it's invaluable to get your data neat and orderly.  In this article, I'll show you how to combine several functions together to better organize your data. g... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/nested-functions-in-google-sheets/</link>
                <guid isPermaLink="false">66b8de1efedc3fd92fddb76a</guid>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ google sheets ]]>
                    </category>
                
                    <category>
                        <![CDATA[ spreadsheets ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Eamonn Cottrell ]]>
                </dc:creator>
                <pubDate>Thu, 23 Feb 2023 01:49:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/nesting-functions-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Data analysis is an extremely valuable skill to have. But to make the most of your analysis, it's invaluable to get your data neat and orderly. </p>
<p>In this article, I'll show you how to combine several functions together to better organize your data.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/giphy.gif" alt="Image" width="600" height="400" loading="lazy">
<em>gif of toys talking to each other saying, data, data everywhere</em></p>
<p>Google Sheets and Microsoft Excel are fantastic training grounds for computer programming. They allow quick access to writing functions that help you creatively solve problems just like in "real" programming. And, they also offer immediate results with the ability to troubleshoot bugs.</p>
<p>Today we'll grab a sample dataset from Kaggle and use it to illustrate:</p>
<ol>
<li>Shortcomings of simple, built-in functions</li>
<li>How to nest functions</li>
<li>How to extract and count unique values from our dataset</li>
</ol>
<h2 id="heading-the-data-and-the-problem">The Data and the Problem</h2>
<p>We're going to look at a dataset from Kaggle that was scrapped from IMDB. It's a list of 1000 movies. The piece we'll concern ourselves with is the genre column.</p>
<p>If you'd like to follow along, the <strong><a target="_blank" href="https://www.kaggle.com/datasets/harshitshankhdhar/imdb-dataset-of-top-1000-movies-and-tv-shows?select=imdb_top_1000.csv">dataset is here</a></strong>, I've built a <a target="_blank" href="https://docs.google.com/spreadsheets/d/1-PfjTvHl2olxAmbrs8LAhP2Dkly9Rp5362YUXIe9RRg/edit#gid=987342418"><strong>spreadsheet here</strong></a> that you can follow along with and even make a copy of, and I've recorded a walkthrough video here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/e1LQnye12-E" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>The issue that we'll solve is this: in the genre column, we want to extract all the unique values and count the number of times the appear. So, how many movies have Drama as a genre, Action as a genre...and so on.</p>
<p>If each cell had only one genre in it, this would be a quick fix. The built-in functions <code>=UNIQUE()</code> and <code>=COUNTIF</code> would solve this for us quickly. </p>
<p>However, most of the movies have more than one genre associated with them:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-217.png" alt="Image" width="600" height="400" loading="lazy">
<em>List of movie genres in a spreadsheet</em></p>
<p>If we try and use <code>=UNIQUE()</code>, we are going to be stuck because <code>=UNIQUE()</code> looks at each cell. So, it will think that the cell containing the value <code>Crime, Drama</code> is one unique value itself instead of knowing that it's a list of two genres. </p>
<p>Below is an example of what happens when using <code>=UNIQUE()</code> on a small portion of our dataset:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/unique.png" alt="Image" width="600" height="400" loading="lazy">
<em>using Unique function in spreadsheet</em></p>
<p>Luckily, spreadsheets are as smart as we're willing to make them. And we are able to use a combination of functions to extract the data we need. </p>
<p>Below, we'll walk through the steps and functions necessary to clean up and analyze our data properly.</p>
<h2 id="heading-the-functions-well-use">The Functions We'll Use</h2>
<p>First, let's take our dataset and get it into one big uniform list where every value is separated by commas since that's the issue above.</p>
<p>To do this, we'll use the <code>=JOIN()</code> function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-220.png" alt="Image" width="600" height="400" loading="lazy">
<em>The join function in Google Sheets</em></p>
<p><code>=JOIN()</code> lets us concatenate elements in our dataset with a delimiter – in our case, a comma and a space: <code>=JOIN(", ",A2:A1001)</code>.</p>
<p>Next, we need to split that huge list so that we get all our values in their own cell. Recall, that this was the shortcoming initially because the <code>=UNIQUE()</code> function returns unique cells.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-221.png" alt="Image" width="600" height="400" loading="lazy">
<em>Split function in Google Sheets</em></p>
<p>The <code>=SPLIT()</code> function takes that huge list of comma-separated values and splits it into separate cells by whatever delimiter we specify. In this case, again, it'll be a comma and a space.</p>
<p>This would split everything across an incredibly long row, though.</p>
<p>So, we'll use the <code>=TRANSPOSE()</code> function to have it displayed down a column instead.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/split.png" alt="Image" width="600" height="400" loading="lazy">
<em>Split and Transposed functions in Google Sheets</em></p>
<p>And we're in business. We can now use our original <code>=UNIQUE()</code> function to grab those unique values...and as an added bonus, the <code>=SORT()</code> function to get them alphabetically sorted.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/oh-yeah.gif" alt="Image" width="600" height="400" loading="lazy">
<em>gif of man rejoicing quietly</em></p>
<h2 id="heading-how-to-nest-the-functions">How to Nest the Functions</h2>
<p>Now that we know what all these do, let's nest them together in one cell to extract those unique values and sort them in a list in one fell swoop:</p>
<p><code>=UNIQUE(SORT(TRANSPOSE(SPLIT(JOIN(", ",A2:A),", ",FALSE))))</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/boom.gif" alt="Image" width="600" height="400" loading="lazy">
<em>gif of girl saying boom</em></p>
<p>Just like in algebra, we nest the functions that we need evaluated first deeper in the statement. So we have the <code>=JOIN()</code> function wrapped in the <code>=SPLIT()</code> function which is itself wrapped in the <code>=TRANSPOSE()</code> function, the <code>=SORT()</code> function and then finally at the very end, our <code>=UNIQUE()</code> function. The result is below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-223.png" alt="Image" width="600" height="400" loading="lazy">
<em>Complete sorted movie genre list</em></p>
<h2 id="heading-a-shorter-nested-function">A Shorter Nested Function</h2>
<p>From here, we can now count the occurrences of each genre in our main list using the <code>=COUNTIF()</code> function in a similar, though smaller nest.</p>
<p>We need to split and join our list first just like we did in the above example: <code>=SPLIT(JOIN(", ",$A$2:$A),", ")</code>.</p>
<p>This becomes our range for the <code>=COUNTIF()</code> function. Then we count the values in that range if they're equal to the cells that hold our unique genre values.</p>
<p>For the Action genre in cell <code>E19</code>, here's the <code>=COUNTIF()</code> function:</p>
<p><code>=COUNTIF(SPLIT(JOIN(", ",$A$2:$A),", "),E19)</code></p>
<p>This returns <code>189</code> as the number of times Action is in our dataset. And by copying the formula down for each of our genres, we now have the number of occurrences of each of the genres. </p>
<p><strong>Note:</strong> make sure to lock the dataset reference in place when you copy the formula down by enclosing the cell references in dollar signs: <code>$A$2:$A</code>. If you don't, then when you copy the formula down, that reference will shift down too.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-224.png" alt="Image" width="600" height="400" loading="lazy">
<em>Number of times each genre appears in dataset</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope this has been helpful for you! Spreadsheet functions are truly a great way to get into programming as well as expand your problem solving skills. I continue to enjoy optimizing my business by automating through spreadsheets.</p>
<p>📽️I'd love if you checked out my YouTube channel over here: <a target="_blank" href="https://www.youtube.com/@eamonncottrell">https://www.youtube.com/@eamonncottrell</a></p>
<p>I'm making content like this all year and would appreciate a like/subscribe. Let me know what other videos/tutorials you'd benefit from!</p>
<p>💥You can also find me on Linkedin here: <a target="_blank" href="https://www.linkedin.com/in/eamonncottrell/">https://www.linkedin.com/in/eamonncottrell/</a></p>
<p>Have a great one! 👋</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Anonymous Function – How to Use Lambda Functions ]]>
                </title>
                <description>
                    <![CDATA[ You can use functions in programming to store a piece of code that can be invoked when needed. This prevents you from retyping the same logic every time you need that code. In this article, you'll learn how to create and use anonymous functions in Py... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-lambda-functions-in-python/</link>
                <guid isPermaLink="false">66b0a2ed7cd8dca6718a2248</guid>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ lambda ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Wed, 15 Feb 2023 17:17:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/lambda-functions-in-python.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use functions in programming to store a piece of code that can be invoked when needed. This prevents you from retyping the same logic every time you need that code.</p>
<p>In this article, you'll learn how to create and use anonymous functions in Python. They are also called lambda functions.</p>
<p>We'll begin with a quick overview of how regular functions are created in Python. Then you'll learn the syntax and practical applications of anonymous functions in Python. </p>
<p>You'll also see some of the differences between lambda and regular functions in Python, and when to use lambda functions.</p>
<h2 id="heading-how-to-use-functions-in-python">How to Use Functions in Python</h2>
<p>Functions prevent you from reinventing the wheel when certain logic is required multiple times.</p>
<p>Consider the code below:</p>
<pre><code class="lang-python">first_addition = <span class="hljs-number">2</span>+<span class="hljs-number">3</span> 
print(first_addition) <span class="hljs-comment"># 5 </span>

second_addition = <span class="hljs-number">3</span>+<span class="hljs-number">5</span> 
print(second_addition) <span class="hljs-comment"># 8</span>
</code></pre>
<p>We had to recreate the logic for addition multiple times in different variables. Imagine if you had to do this a hundred times.</p>
<p>With a function, you can create the logic once and reuse it as much as you want to. Here's an example in Python:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add_numbers</span>(<span class="hljs-params">a,b</span>):</span> <span class="hljs-keyword">return</span> a + b 

print(add_numbers(<span class="hljs-number">2</span>,<span class="hljs-number">3</span>)) <span class="hljs-comment"># 5 </span>
print(add_numbers(<span class="hljs-number">3</span>,<span class="hljs-number">5</span>)) <span class="hljs-comment"># 8 </span>
print(add_numbers(<span class="hljs-number">5</span>,<span class="hljs-number">7</span>)) <span class="hljs-comment"># 12</span>
</code></pre>
<p>Using the <code>def</code> keyword, we created a function called <code>add_numbers(a,b)</code>. It takes two parameters – <code>a</code> and <code>b</code>. The function returns the sum of <code>a</code> and <code>b</code>.</p>
<p>So to use the logic multiple times, we just had to call the function and pass in different parameters for different operations:</p>
<pre><code class="lang-python">print(add_numbers(<span class="hljs-number">2</span>,<span class="hljs-number">3</span>)) <span class="hljs-comment"># 5 </span>
print(add_numbers(<span class="hljs-number">3</span>,<span class="hljs-number">5</span>)) <span class="hljs-comment"># 8 </span>
print(add_numbers(<span class="hljs-number">5</span>,<span class="hljs-number">7</span>)) <span class="hljs-comment"># 12</span>
</code></pre>
<p>Now let's take a look at anonymous/lambda functions in Python.</p>
<h2 id="heading-how-to-use-lambda-functions-in-python">How to Use Lambda Functions in Python</h2>
<p>An anonymous function in Python is a function without a name. It can be immediately invoked or stored in a variable.</p>
<p>Anonymous functions in Python are also known as lambda functions.</p>
<p>Here's the syntax for creating a lambda function in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">lambda</span> parameter(s) : expression
</code></pre>
<p>There are three values that define a lambda function as seen in the syntax above:</p>
<ul>
<li>A lambda function is created using the <code>lambda</code> keyword.</li>
<li>The keyword is followed by one or many parameters.</li>
<li>Lastly, an expression is provided for the function. This is the part of the code that gets executed/returned. </li>
</ul>
<p>The parameter(s) and expression are separated by a colon.</p>
<p>Here's an example:</p>
<pre><code class="lang-python">add_numbers = <span class="hljs-keyword">lambda</span> a,b : a + b 

print(add_numbers(<span class="hljs-number">2</span>,<span class="hljs-number">3</span>)) <span class="hljs-comment"># 5</span>
</code></pre>
<p>In the code above, we created a lambda function with two parameters – <code>a</code> and <code>b</code>. The function returns the sum of the parameters.</p>
<p>That is: <code>lambda a,b : a + b</code> </p>
<p>Note that the function has no name. We assigned the lambda function to a variable called <code>add_numbers</code> so that we can easily invoke the function through the variable. </p>
<p>Without assigning a lambda function to a variable, you'd have something like this:</p>
<pre><code class="lang-python">print(<span class="hljs-keyword">lambda</span> a,b : a + b)
<span class="hljs-comment"># &lt;function &lt;lambda&gt; at 0x7f757922fb00&gt;</span>
</code></pre>
<p>The code above simply returns a lambda object in the console. </p>
<p>You can immediately call a lambda function using parenthesis:</p>
<pre><code class="lang-python">(<span class="hljs-keyword">lambda</span> a,b : a + b)(<span class="hljs-number">2</span>,<span class="hljs-number">3</span>)
</code></pre>
<p>When the code above is printed, you'll get 5 returned.</p>
<h2 id="heading-what-is-the-difference-between-lambda-and-regular-functions-in-python">What Is the Difference Between Lambda and Regular Functions in Python?</h2>
<p>Here are some differences between lambda functions and regular functions in Python:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Lambda functions</td><td>Regular functions</td></tr>
</thead>
<tbody>
<tr>
<td>Defined using the lambda keyword</td><td>Defined using the def keyword</td></tr>
<tr>
<td>Can be written in one line</td><td>Requires more than one line of code</td></tr>
<tr>
<td>No return statement required</td><td>Return statement must be defined when returning values</td></tr>
<tr>
<td>Can be used anonymously</td><td>Regular functions must be given a name</td></tr>
</tbody>
</table>
</div><h2 id="heading-when-to-use-a-lambda-function-in-python">When to Use a Lambda Function in Python</h2>
<p>Although you can use both regular functions and lambda functions to achieve the same results, here are some of the reasons why you might pick a lambda function:</p>
<p>First of all, you can use a lambda function when you need a function that'll be used just once. This is especially useful when working with functions like <code>map</code>, <code>reduce</code>, <code>filter</code>. Consider the code below:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">double_number</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">return</span> n + n

numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>]

double_result = map(double_number, numbers)

print(list(double_result))
<span class="hljs-comment"># [2, 6, 10, 14, 18]</span>
</code></pre>
<p>In the code above, we created a regular function called <code>double_number</code> which doubles the value of a number. </p>
<p>Although the function was passed in as a parameter to the <code>map</code> function — <code>map(double_number, numbers)</code>, we had to write the logic before using it. </p>
<p>With lambda functions, you can do this: </p>
<pre><code class="lang-python">numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>]

double_result = map(<span class="hljs-keyword">lambda</span> x : x+x, numbers)

print(list(double_result))
<span class="hljs-comment"># [2, 6, 10, 14, 18]</span>
</code></pre>
<p>As you can see above, we just passed a lambda function — <code>lambda x : x+x</code> — as a parameter to the <code>map</code> function: <code>map(lambda x : x+x, numbers)</code>.</p>
<p>We were able to achieve the same result with fewer lines of code. There was no need for defining a function first before use. </p>
<p>You can also use a lambda function when you need a function that should be invoked immediately. As you can see in the example in the previous point, we first defined the regular function before using it. Lambda functions can be invoked immediately after creating them.</p>
<p>Finally, lambdas are useful when you want to use a function inside a function. Or when you want to create a function that returns a function.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about lambda functions in Python. There are functions without a name and can be executed with a single line of code. </p>
<p>We saw how to use regular functions in Python with some examples. </p>
<p>We then saw the syntax and a practical example of using lambda functions. </p>
<p>Lastly, we talked about the differences between lambda functions and regular functions in Python, and when to use lambda functions.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Functions Work in JavaScript – JS Function Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is a widely-used programming language that is essential for web development. Its ability to run on both client-side and server-side makes it a versatile tool that has become an essential tool for web developers. JavaScript is a high-level,... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/understanding-functions-in-javascript/</link>
                <guid isPermaLink="false">66c8c879fe21816c4cb75d0b</guid>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Fri, 20 Jan 2023 17:52:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/kevin-ku-w7ZyuGYNpRQ-unsplash-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is a widely-used programming language that is essential for web development. Its ability to run on both client-side and server-side makes it a versatile tool that has become an essential tool for web developers.</p>
<p>JavaScript is a high-level, interpreted language used on the client side, meaning it runs in the user's web browser. You can use it to create web and mobile applications, browser extensions, and other software. </p>
<p>It is supported by all major web browsers, and it is an essential technology for front-end web development. </p>
<p><strong>Functions</strong> are one of the building blocks of JavaScript programming for creating web applications. </p>
<p>You can think of functions as a way to group a set of instructions together and execute them as a single unit. </p>
<p>In this article, we will explore the basics of functions in JavaScript and how you can use them effectively in your code.</p>
<h2 id="heading-function-syntax">Function Syntax</h2>
<p>A function is a block of code that performs a specific task. JavaScript functions are basically used to encapsulate logic, making that code more reusable and easier to understand. </p>
<p>The syntax for creating a function in JavaScript is quite simple. Functions can take input in the form of parameters and can return a value or output. </p>
<p>Functions help you organize and structure your code. They also allow for code reuse and make it easier to understand and maintain large codebases.</p>
<h3 id="heading-how-to-write-a-function-in-javascript">How to Write a Function in JavaScript</h3>
<p>You start by using the keyword "<strong>function</strong>," followed by the function name and a set of parentheses. </p>
<p>Inside the parentheses, you can specify any input parameters that the function will take in, also known as arguments. The arguments are usually optional. </p>
<p>Next, you include a block of code inside curly braces that defines the instructions the function will execute when it is called. </p>
<p>Here is an example of a basic function that takes in two numbers and returns their sum:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>The function above, named "<strong>addNumbers</strong>," takes in two parameters, <strong>a</strong> and <strong>b</strong>. The code inside the function body simply adds these two parameters together and returns the result.</p>
<h2 id="heading-how-to-declare-a-function-in-javascript">How to Declare a Function in JavaScript</h2>
<p>Apart from the regular way of declaring a function as seen above, you can also define functions using <strong>function expressions</strong> or <strong>arrow functions</strong>. </p>
<p>The arrow function syntax is a shorthand version of the regular function syntax. Here is the same function as above, but written with an arrow function:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>
<span class="hljs-keyword">const</span> addNumbers = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b;
</code></pre>
<p>In the example above, the function is assigned to the variable <strong>addNumbers</strong>. The arrow <strong>=&gt;</strong> is used to define the function, and the code inside the curly braces is the body of the function.</p>
<p>Function expressions in JavaScript are similar to regular function declarations. The difference between them is that the function expression is always assigned to a variable. Here is an example of a function expression:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>
<span class="hljs-keyword">let</span> multiplyNumbers = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a * b;
}
</code></pre>
<p>In this example, the function is assigned to the variable <strong>multiplyNumbers</strong>. This variable can be used to call the function, just like a regular function.</p>
<h2 id="heading-how-to-use-callback-functions">How to Use Callback Functions</h2>
<p>Functions can also be passed as arguments to other functions, known as <strong>callback functions</strong>. Here is an example of a callback function being used to log the result of a multiplication operation:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiplyByTwo</span>(<span class="hljs-params">n, callback</span>) </span>{
  <span class="hljs-keyword">var</span> result = n * <span class="hljs-number">2</span>;
  callback(result);
}

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

multiplyByTwo(<span class="hljs-number">5</span>, logResult); <span class="hljs-comment">// logs 10</span>
</code></pre>
<p>In this example, the <strong>multiplyByTwo</strong> function takes two arguments: a number and a callback function. The function multiplies the number by 2 and then invokes the callback function, passing the result as an argument. The <strong>logResult</strong> function is then executed, which logs the result to the console.</p>
<h2 id="heading-how-to-use-default-parameters">How to Use Default Parameters</h2>
<p>JavaScript functions also have a feature called default parameters. They allow you to set default values for parameters in case they are not passed when the function is called. </p>
<p>This is helpful in situations where you want to provide a default value for a parameter in case it is not passed. Here is an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

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

greet(); <span class="hljs-comment">// Hello, John Doe!</span>
greet(<span class="hljs-string">"Jane Smith"</span>); <span class="hljs-comment">// Hello, Jane Smith</span>
</code></pre>
<p>In this example, the <code>greet</code> function takes in a single parameter <code>name</code>, which is set to "John Doe" by default. If the function is called without passing any arguments, it will use the default value "John Doe". But if an argument is passed, it will use that value instead.</p>
<h2 id="heading-how-to-use-the-constructor-function">How to Use the Constructor Function</h2>
<p>JavaScript has a special type of function called a constructor function, which is used to create objects. </p>
<p>You define a constructor function using the keyword "function" followed by a name that starts with an uppercase letter (called using the "new" keyword). </p>
<p>For example, the following code defines a constructor function named "Person" that creates an object with a name and age property:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name, age</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.age = age;
}

<span class="hljs-keyword">let</span> person = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"John Smith"</span>, <span class="hljs-number">30</span>);
<span class="hljs-built_in">console</span>.log(person.name); <span class="hljs-comment">// Output: "John Smith"</span>
<span class="hljs-built_in">console</span>.log(person.age);
</code></pre>
<h2 id="heading-how-to-use-closures">How to Use Closures</h2>
<p>A <strong>closure</strong> is a function that has access to variables in its parent scope, even after the parent function has returned. This allows for variables to be preserved between function calls, and it is a powerful feature that allows for more advanced programming patterns such as object-oriented programming. </p>
<p>Here's an example of a closure function that creates a counter:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createCounter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> count++;
  }
}
<span class="hljs-keyword">const</span> myCounter = createCounter();
<span class="hljs-built_in">console</span>.log(myCounter()); <span class="hljs-comment">// Output: 0</span>
<span class="hljs-built_in">console</span>.log(myCounter()); /
</code></pre>
<h2 id="heading-how-to-use-higher-order-functions">How to Use Higher-Order Functions</h2>
<p>Functions can also be passed as arguments to other functions, which is known as a "higher-order" function. For example:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">performOperation</span>(<span class="hljs-params">a, b, operation</span>) </span>{
    <span class="hljs-keyword">return</span> operation(a, b);
}

<span class="hljs-keyword">let</span> result = performOperation(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, addNumbers);
<span class="hljs-built_in">console</span>.log(result);  <span class="hljs-comment">// 15</span>
</code></pre>
<p>In this example, the <strong>performOperation</strong> function takes in three arguments: <strong>a</strong>, <strong>b</strong>, and <strong>operation</strong>. </p>
<p>The <strong>operation</strong> argument is a function that takes in two arguments and returns a result. In this case, we are passing the <strong>addNumbers</strong> function as the operation argument, so the result of the <strong>performOperation</strong> function will be the result of calling the <strong>addNumbers</strong> function with the arguments <strong>a</strong> and <strong>b</strong>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we have covered the basics of functions in JavaScript, including how to define, call, and use them in our codes. </p>
<p>With a solid understanding of functions, you can write more efficient and maintainable code in JavaScript.</p>
<p>You can check the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions">MDN docs</a> to read more about functions in JavaScript. If you want to start learning the fundamentals of JavaScript, freeCodeCamp has a free <a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/">JavaScript Algorithms and Data Structures Certification</a> course for you.  </p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Organize Your Code with Functions ]]>
                </title>
                <description>
                    <![CDATA[ By Deborah Kurata Functions are a fundamental building block of programming. They help us organize our code into manageable and reusable pieces.  Let's explore the basics of functions by way of a burger joint. A burger joint may seem like an odd plac... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/organizing-code-with-functions/</link>
                <guid isPermaLink="false">66d45e10f855545810e93429</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learning to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 19 Jan 2023 17:29:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/organizing-code-with-functions-thumbnail.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Deborah Kurata</p>
<p>Functions are a fundamental building block of programming. They help us organize our code into manageable and reusable pieces. </p>
<p>Let's explore the basics of functions by way of a burger joint.</p>
<p>A burger joint may seem like an odd place to learn about code organization...but let's see where this goes. And you can view the associated video here.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/3f4g8RwELC4" 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>Are you hungry for some knowledge? Or maybe a burger?</p>
<p>Tackling any large set of tasks requires some amount of organization. Say we work at a burger restaurant. We could define a simplified view of the process as shown below:</p>
<ol>
<li>Take a customer's order</li>
<li>If the customer ordered fries, make fries:<ul>
<li>Dump fries into the fryer</li>
<li>Set a timer</li>
<li>Etc.</li>
</ul>
</li>
<li>If the customer ordered a burger, make the burger:<ul>
<li>Select the appropriate type of patty (veggie, chicken, fish, beef)</li>
<li>Fry the burger</li>
<li>Toast the bun</li>
<li>Etc.</li>
</ul>
</li>
<li>Put the items in a box</li>
<li>Repeat at step 1</li>
</ol>
<p>A worker takes a customer's order. If the customer ordered fries, they make fries. Notice the "sub-list" describing how to make the fries. And if the customer ordered a burger, they make the burger. And there's another "sub-list" describing how to make the burger.</p>
<p>To keep our main list of instructions straightforward and easier to follow, we can move these sub-lists to separate sets of instructions.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/figure3.jpg" alt="Make Fries sub-steps shown in one box. Make a Burger sub-steps shown in a second box. Steps without the sub-steps shown on the right." width="600" height="400" loading="lazy">
<em>Figure 1. Defining functions</em></p>
<p>The left side of Figure 1 shows the list of steps for making fries, and the list for making a burger. We reference those instructions in the main flow, as shown on the right side of Figure 1. </p>
<p>The result is that each separate list of instructions is clearly defined. And the main flow on the right is easier to see without all of the sub-lists.</p>
<p>In programming, we call each of these self-contained sets of instructions a <strong>function</strong>.</p>
<p>Let's stop at this point and think about this. What are some benefits of breaking out some of the instructions into functions? Thoughts?</p>
<p>Separating our code into functions has several advantages:</p>
<ul>
<li>When building or maintaining the function, we can focus just on that function: what information it needs, what steps it performs, and what result it provides.</li>
<li>We can simplify the main set of instructions, making it easier to read and maintain over time.</li>
<li>It helps us separate work for a team, assigning each independent function to a member of the team. Jesse can be making fries, Chris making the burgers, and Sandhya follows the main flow, taking orders.</li>
<li>And we can more easily reuse the function in multiple places in the application.</li>
</ul>
<p>Did you think of other benefits?</p>
<h2 id="heading-what-is-a-function">What Is a Function?</h2>
<p>In programming:</p>
<ul>
<li>A <strong>function</strong> is a self-contained set of instructions to accomplish a chunk of a larger task.</li>
<li>A function separates responsibilities for a specific part of a task, making the main task easier to work with and read.</li>
<li>Functions add structure to our programs, and make them easier to read and modify over time.</li>
</ul>
<p>Here is a tip: Code is often read much more often than it's written, so make your code readable.</p>
<h2 id="heading-anatomy-of-a-function">Anatomy of a Function</h2>
<p>When writing code, functions look something like this:</p>
<h3 id="heading-make-fries">Make Fries</h3>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">makeFries</span>(<span class="hljs-params">fries</span>) </span>{
  ... instructions go here ...
  return cookedFries
}
</code></pre><h3 id="heading-make-a-burger">Make a Burger</h3>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">makeBurger</span>(<span class="hljs-params">patty, bun, condiments</span>) </span>{
  ... instructions go here ...
  return cookedBurger
}
</code></pre><p>Note that the details of the functions may look a bit different depending on the programming language you use.</p>
<p>A function often takes in some information, performs the set of instructions using that information, and gives back (or "returns") a result. At the burger joint we can say: "Hey Chris, here is a patty, bun, and condiments, go make the burger, and bring it back to me when it's done."</p>
<p>Functions are often named with the task they perform following a verbObject style naming convention: makeFries and makeBurger.</p>
<p>The name is followed by a list of the information that the function needs. In this example, this information is enclosed in parenthesis and separated with commas. For our makeFries, we need the fries. And for the burger, we need a patty, bun, and condiments.</p>
<p>The function body contains the set of instructions required for this function.</p>
<p>In many cases, a function performs its set of steps and returns a result. So lastly, we return that result. The result is often indicated with a return statement. In this example, when the fries are made or the burger is done, we pass them back to the main flow and they are boxed for the customer.</p>
<h2 id="heading-how-to-create-a-function">How to Create a Function</h2>
<p>Let's look at another example from a simple virtual pet adoption website as shown in Figure 2.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/figure5.jpg" alt="Screen shot of a web page that asks for the type of pet (cat) and how many (3), then displays &quot;meow&quot; three times." width="600" height="400" loading="lazy">
<em>Figure 2. Virtual pet adoption website</em></p>
<p>The user enters the type and number of pets, and clicks Adopt. The application then displays a message and a greeting from each of the virtually adopted pets.</p>
<p>When writing the code for this website, we want to simplify the main set of instructions by separating out the feature that prepares the pet greeting. We define a function for those instructions like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">prepareGreeting</span>(<span class="hljs-params">typeOfPet, numberOfPets</span>) </span>{ 
  <span class="hljs-keyword">var</span> greeting = <span class="hljs-string">''</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numberOfPets; i++) {
    <span class="hljs-keyword">if</span> (typeOfPet === <span class="hljs-string">'cat'</span>) { 
      greeting += <span class="hljs-string">'meow'</span> + <span class="hljs-string">'&lt;br/&gt;'</span>;
    }
    <span class="hljs-keyword">if</span> (typeOfPet === <span class="hljs-string">'dog'</span>) { 
      greeting += <span class="hljs-string">'woof'</span> + <span class="hljs-string">'&lt;br/&gt;'</span>;
    }
  }
  <span class="hljs-keyword">return</span> greeting;
}
</code></pre>
<p>This function is named "prepareGreeting" following our verbObject convention. It's best practice to give every function a meaningful name.</p>
<p>For a function to perform its set of instructions, it often needs some information. In this case, it needs the type of pet and the number of pets. When creating a function, we identify that needed information using parameters. </p>
<p>A <strong>parameter</strong> is a placeholder for the information the function needs. We give each placeholder a descriptive name, such as typeOfPet and numberOfPets. We add the parameters after the function name, often within parentheses and separated with commas.</p>
<p>The function name with its set of parameters is called a <strong>function signature</strong>. The function signature uniquely identifies the function.</p>
<p>The <strong>function body</strong> is where we write the code to perform the set of instructions. In this example, it's where we prepare the greeting. </p>
<p>In programming languages that use curly braces, the function body is defined between the first and last curly brace. In some languages, the function body is defined simply by its indentation.</p>
<p>In this function body, we prepare the pet's greeting. First, we initialize a greeting variable to an empty string. This ensures that we have a string (or text) variable we can use for the greeting text.</p>
<p>Then we loop for each pet. We use a counter represented by "i", repeat the loop while our counter is less than the total number of pets, and increment "i" at the end of each loop. Notice that in most programming languages, counting is zero-based, meaning it counts the iterations of the loop starting at 0: 0, 1, 2 for three pets.</p>
<p>Within the loop, if the passed-in pet type is a cat, we add a "meow" for each pet to the greeting variable. If the passed in pet type is a dog, we append "woof" for each pet. We then return that resulting greeting to the main set of instructions.</p>
<h2 id="heading-how-to-call-a-function">How to Call a Function</h2>
<p>Code in a function won't do anything until we call that function from some other code, such as our main set of instructions. The exact syntax for calling a function depends on the programming language you use. But it will look something like this:</p>
<pre><code class="lang-js">greetingForDisplay = prepareGreeting(<span class="hljs-string">"cat"</span>, <span class="hljs-number">3</span>)
</code></pre>
<p>We use the name of the function to identify which function we want to call. Then pass a value in for each parameter placeholder. In this example, we pass in a string (or text) using quotation marks and a number.</p>
<p>The result of the function's instructions are returned to the code that called it. In this example, the value is assigned to the greetingForDisplay variable. The main code could then display the contents of this variable to the user.</p>
<p>When working with functions, be sure to keep these two terms clear:</p>
<ul>
<li><strong>Parameter</strong>: The placeholder in the function signature where we define what kind of information the function needs.</li>
<li><strong>Argument</strong>: The value(s) passed in when calling the function, giving the function the information it needs to perform its instructions</li>
</ul>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>We use a function to define a self-contained set of instructions for a chunk of a larger task. Using functions helps break up long code into manageable pieces. Just like building blocks, we combine functions to create simple to complex applications and websites.</p>
<p>For more information on general programming concepts, check out my course: <a target="_blank" href="https://www.youtube.com/playlist?list=PLErOmyzRKOCrO9bwM1931IY8S3iWfhrr8">"Gentle Introduction to Programming for Beginners"</a>. And for information on web development, GitHub, Angular, and C#, subscribe to <a target="_blank" href="https://www.youtube.com/@deborah_kurata">my YouTube channel</a>.</p>
<p>Now, let's go order that burger!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Higher Order Functions in JavaScript – Explained with Practical Examples ]]>
                </title>
                <description>
                    <![CDATA[ As a web developer, you should always strive to learn new techniques and discover ways to work smarter with JavaScript. One such technique is using higher order functions. Higher order functions are functions that take one or more functions as argume... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/</link>
                <guid isPermaLink="false">66d46149868774922c885020</guid>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sobit Prasad ]]>
                </dc:creator>
                <pubDate>Tue, 03 Jan 2023 22:11:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/higher-order-functions-in-javascript-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As a web developer, you should always strive to learn new techniques and discover ways to work smarter with JavaScript.</p>
<p>One such technique is using higher order functions. Higher order functions are functions that take one or more functions as arguments, or return a function as their result.</p>
<p>In this article, we will delve into what a higher order function is, the benefits of using them, and how to use them in practical applications.</p>
<h2 id="heading-what-is-a-higher-order-function">What is a Higher Order Function?</h2>
<p>A higher order function is a function that takes one or more functions as arguments, or returns a function as its result.</p>
<p>There are several different types of higher order functions like map and reduce. We will discuss these later in this tutorial. But before that let's first dive deep into what higher order functions are.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Callback function, passed as a parameter in the higher order function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am  a callback function'</span>);
}

<span class="hljs-comment">// higher order function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">higherOrderFunction</span>(<span class="hljs-params">func</span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am higher order function'</span>)
    func()
}

higherOrderFunction(callbackFunction);
</code></pre>
<p>In the above code <code>higherOrderFunction()</code> is an HOF because we are passing a callback function as a parameter to it.</p>
<p>The above example is quite simple isn't it? So let's expand it further and see how you can use HOFs to write more concise and modular code.</p>
<h3 id="heading-how-higher-order-functions-work">How Higher Order Functions Work</h3>
<p>So, suppose I want you to write a function that calculates the area and diameter of a circle. As a beginner, the first solution that comes to our mind is to write each separate function to calculate area or diameter.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> radius = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// function to calculate area of the circle</span>
<span class="hljs-keyword">const</span> calculateArea =  <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">radius</span>) </span>{
    <span class="hljs-keyword">const</span> output = [];
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i&lt; radius.length; i++){
        output.push(<span class="hljs-built_in">Math</span>.PI * radius[i] * radius[i]);
    }
    <span class="hljs-keyword">return</span> output;
}
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// function to calculate diameter of the circle</span>
<span class="hljs-keyword">const</span> calculateDiameter =  <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">radius</span>) </span>{
    <span class="hljs-keyword">const</span> output = [];
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i&lt; radius.length; i++){
        output.push(<span class="hljs-number">2</span> * radius[i]);
    }
    <span class="hljs-keyword">return</span> output;
}
</code></pre>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(calculateArea(radius));
<span class="hljs-built_in">console</span>.log(calculateDiameter(radius))
</code></pre>
<p>But have you noticed the problem with the above code? Aren't we writing almost the same function again and again with slightly different logic? Also, the functions we have written aren't reusable, are they?</p>
<p>So, let's see how we can write the same code using HOFs:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> radius = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// logic to clculate area</span>
<span class="hljs-keyword">const</span> area = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">radius</span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.PI * radius * radius;
}
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// logic to calculate diameter</span>
<span class="hljs-keyword">const</span> diameter = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">radius</span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-number">2</span> * radius;
}
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// a reusable function to calculate area, diameter, etc</span>
<span class="hljs-keyword">const</span> calculate = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">radius, logic</span>)</span>{ 
    <span class="hljs-keyword">const</span> output = [];
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; radius.length; i++){
        output.push(logic(radius[i]))
    }
    <span class="hljs-keyword">return</span> output;
}
</code></pre>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(calculate(radius, area));
<span class="hljs-built_in">console</span>.log(calculate(radius, diameter));
</code></pre>
<p>Now, as you can see in the above code, we have only written a single function <code>calculate()</code> to calculate the area and diameter of the circle. We only need to write the logic and pass it to <code>calculate()</code> and the function will do the job.</p>
<p>The code that we have written using HOFs is concise and modular. Each function is doing its own job and we are not repeating anything here.</p>
<p>Suppose in the future if we want to write a program to calculate the circumference of the circle. We can simply write the logic to calculate the circumference and pass it to the <code>calculate()</code> function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> circumeference = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">radius</span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-number">2</span> * <span class="hljs-built_in">Math</span>.PI * radius;
}
</code></pre>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(calculate(radius, circumeference));
</code></pre>
<h2 id="heading-how-to-use-higher-order-functions">How to Use Higher Order Functions</h2>
<p>You can use higher order functions in a variety of ways.</p>
<p>When working with arrays, you can use the <code>map()</code>, <code>reduce()</code>, <code>filter()</code>, and <code>sort()</code> functions to manipulate and transform data in an array.</p>
<p>When working with objects, you can use the <code>Object.entries()</code> function to create a new array from an object.</p>
<p>When working with functions, you can use the <code>compose()</code> function to create complex functions from simpler ones.</p>
<h2 id="heading-how-to-use-some-important-higher-order-functions">How to Use Some Important Higher Order Functions</h2>
<p>There are various built in HOFs, and some of the most common ones are map(), filter() and reduce(). So let's understand each one of these in detail.</p>
<h3 id="heading-how-to-use-map-in-javascript"><strong>How to use</strong> <code>map()</code> in JavaScript</h3>
<p>The <code>map()</code> function takes an array of values and applies a transformation to each value in the array. It does not mutate the original array. It is often used to transform an array of data into a new array with a different structure.</p>
<p>Let's understand with the help of examples.</p>
<p><strong>Example 1</strong>: Suppose we want to add 10 to every element in a array. We can use the <code>map()</code> method to map over every element in the array to add 10 to it.</p>
<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-keyword">const</span> output = arr.map(<span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> num += <span class="hljs-number">10</span>)
<span class="hljs-built_in">console</span>.log(arr); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
<span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">// [11, 12, 13, 14, 15]</span>
</code></pre>
<p>In the above example, <code>arr</code> is an array with five elements: 1, 2, 3, 4, and 5. <code>map</code> is a method that we use to apply a function to each element in an array, and it returns a new array with the modified elements.</p>
<p>The callback function that is being passed to <code>map</code> uses the arrow function syntax, and it takes a single argument <code>num</code>. This function adds 10 to <code>num</code> (every element in the array) and returns the result.</p>
<p><strong>Example 2</strong>: Here we have an array of users. Suppose we only want their first and last name. We can simply use the <code>map()</code> method to extract it from the <code>users</code> array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> users = [
    {<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">25</span>},
    {<span class="hljs-attr">firstName</span>: <span class="hljs-string">'Jane'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Doe'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>},
    {<span class="hljs-attr">firstName</span>: <span class="hljs-string">'Jack'</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">firstName</span>: <span class="hljs-string">'Jill'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Doe'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">40</span>},
    {<span class="hljs-attr">firstName</span>: <span class="hljs-string">'Joe'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Doe'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">45</span>},
]

<span class="hljs-keyword">const</span> result = users.map(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> user.firstName + <span class="hljs-string">' '</span> + user.lastName)
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// ['John Doe', 'Jane Doe', 'Jack Doe', 'Jill Doe', 'Joe Doe']</span>
</code></pre>
<p>In the above code, <code>users</code> is an array of objects representing users. Each object has three properties: <code>firstName</code>, <code>lastName</code>, and <code>age</code>.</p>
<p>We are mapping over each user using the <code>map()</code> method to extract the properties <code>firstName</code> and <code>lastName</code>.</p>
<p>The callback function takes a single argument <code>user</code> which represents an element in the <code>users</code> array (an object).</p>
<p>The function concatenates the <code>firstName</code> and <code>lastName</code> properties of the <code>user</code> object, and returns the result.</p>
<h3 id="heading-how-to-use-filter-in-javascript"><strong>How to Use</strong> <code>filter()</code> in JavaScript</h3>
<p>The <code>filter()</code> function takes an array and returns a new array with only the values that meet certain criteria. It also does not mutate the original array. It is often used to select a subset of data from an array based on certain criteria.</p>
<p><strong>Example 1</strong>: You can use <code>filter()</code> to return only the odd numbers from an array of numbers.</p>
<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-keyword">const</span> output = arr.filter(<span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> num % <span class="hljs-number">2</span>) <span class="hljs-comment">// filter out odd numbers</span>
<span class="hljs-built_in">console</span>.log(arr); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
<span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">// [1, 3, 5]</span>
</code></pre>
<p>In the above code, <code>arr</code> is an array with five elements: 1, 2, 3, 4, and 5. <code>filter</code> is a method that is used to create a new array with elements that pass a test specified in a provided callback function.</p>
<p>This callback function checks if <code>num</code> is odd by checking if it is not divisible by 2 (<code>num % 2</code>). If <code>num</code> is not divisible by 2, the function returns <code>true</code>, otherwise it returns <code>false</code>.</p>
<p>When <code>filter</code> is called on <code>arr</code>, it applies this function to each element in the array, creating a new array with only the elements that returned <code>true</code> or passed the specified condition when passed to the function. The original <code>arr</code> remains unchanged and returns the result.</p>
<p><strong>Example 2</strong>: You can use <code>filter()</code> to return only the users having age greater than 30 in an array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> users = [
    {<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">25</span>},
    {<span class="hljs-attr">firstName</span>: <span class="hljs-string">'Jane'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Doe'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>},
    {<span class="hljs-attr">firstName</span>: <span class="hljs-string">'Jack'</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">firstName</span>: <span class="hljs-string">'Jill'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Doe'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">40</span>},
    {<span class="hljs-attr">firstName</span>: <span class="hljs-string">'Joe'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Doe'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">45</span>},
]

<span class="hljs-comment">// Find the users with age greater than 30</span>
<span class="hljs-keyword">const</span> output = users.filter(<span class="hljs-function">(<span class="hljs-params">{age}</span>) =&gt;</span> age &gt; <span class="hljs-number">30</span>)
<span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">// [{firstName: 'Jack', lastName: 'Doe', age: 35}, {firstName: 'Jill', lastName: 'Doe', age: 40}, {firstName: 'Joe', lastName: 'Doe', age: 45}]</span>
</code></pre>
<p>In the above code, <code>users</code> is an array of objects representing users. Each object has three properties: <code>firstName</code>, <code>lastName</code>, and <code>age</code>.</p>
<p><code>filter</code> is called on the <code>users</code> array and it applies a callback function to each element in the array.</p>
<p>The function takes a single argument, an object destructured to a single property <code>age</code>. This function checks if <code>age</code> is greater than 30. If it is, the function returns <code>true</code>, otherwise it returns <code>false</code>.</p>
<p>When <code>filter</code> is called on <code>users</code>, it applies this function to each element in the array, creating a new array with only the elements that returned <code>true</code> when passed to the function and returns the result. The original <code>users</code> array remains unchanged.</p>
<h3 id="heading-how-to-use-reduce-in-javascript"><strong>How to use</strong> <code>reduce()</code> in JavaScript</h3>
<p>The <code>reduce()</code> method is kind of overwhelming. If you have came across <code>reduce()</code> method before and haven't understood it at first, it's totally fine.</p>
<p>But don't worry – here, we will learn it through quite a few examples and I will try my best to make you understand this method.</p>
<p>Now, one doubt that might comes to your mind is why we use the <code>reduce()</code> method. As there are already lots of methods, how can we decide which one to use and when?</p>
<p>In the case of the <code>reduce()</code> method, you should is used it when you want to perform some operation on the elements of an array and return a single value as a result. The "single value" refers to the accumulated result of repeatedly applying a function to the elements of a sequence.</p>
<p>For example, you might use <code>reduce()</code> to sum up all the elements in an array, to find the maximum or minimum value, to merge multiple objects into a single object, or to group different elements in an array.</p>
<p>Now let's understand all these with the help of examples.</p>
<p><strong>Example 1</strong>: Using <code>reduce()</code> to sum up all the elements in an array:</p>
<pre><code class="lang-js"><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-keyword">const</span> sum = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">total, currentValue</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> total + currentValue;
}, <span class="hljs-number">0</span>)

<span class="hljs-built_in">console</span>.log(sum); <span class="hljs-comment">// 15</span>
</code></pre>
<p>In this example, the <code>reduce()</code> method is called on the <code>numbers</code> array and is passed a callback function that takes two arguments: <code>total</code> and <code>currentValue</code>.</p>
<p>The <code>total</code> argument is the accumulation of the values that have been returned from the function so far, and the <code>currentValue</code> is the current element being processed in the array.</p>
<p>The <code>reduce()</code> method also takes an initial value as the second argument, in this case <code>0</code>, which is used as the initial value of <code>total</code> for the first iteration.</p>
<p>In each iteration, the function adds the current value to the total and returns the new value of the total.</p>
<p>The <code>reduce()</code> method then uses the returned value as the <code>total</code> for the next iteration, until it has processed all the elements in the array.</p>
<p>Finally, it returns the final value of the total, which is the sum of all the elements in the array.</p>
<p><strong>Example 2</strong>: Using <code>reduce()</code> to find the maximum value in an array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">5</span>, <span class="hljs-number">20</span>, <span class="hljs-number">100</span>, <span class="hljs-number">60</span>, <span class="hljs-number">1</span>];
<span class="hljs-keyword">const</span> maxValue = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">max, curr</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(curr &gt; max) max = curr;
    <span class="hljs-keyword">return</span> max;
});
<span class="hljs-built_in">console</span>.log(maxValue); <span class="hljs-comment">// 100</span>
</code></pre>
<p>In this example, again we have two arguments <code>max</code> and <code>curr</code> in the callback function. Notice we haven't passed the second parameter in the <code>reduce()</code> method this time. So, the default value will be the first element in the array.</p>
<p>The callback function first checks if the current element <code>curr</code> is greater than the current maximum value <code>max</code>. If it is, it updates the value of <code>max</code> to be the current element. If it is not, <code>max</code> is not updated. Finally, the function returns the value of <code>max</code>.</p>
<p>In this case, the <code>reduce()</code> method will start by setting <code>max</code> to 5 and <code>curr</code> to 20. It will then check if 20 is greater than 5, which it is, so it updates <code>max</code> to 20.</p>
<p>It will then set <code>curr</code> to 100 and check if 100 is greater than 20, which it is, so it updates <code>max</code> to 100.</p>
<p>It will continue this process until it has processed all the elements in the array. The final value of <code>max</code> will be the maximum value in the array, which is 100 in this case.</p>
<p><strong>Example 3</strong>: Using <code>reduce()</code> to merge different objects in a single object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj1 = { <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-keyword">const</span> obj2 = { <span class="hljs-attr">c</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">d</span>: <span class="hljs-number">4</span> };
<span class="hljs-keyword">const</span> obj3 = { <span class="hljs-attr">e</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">f</span>: <span class="hljs-number">6</span> };
<span class="hljs-keyword">const</span> mergedObj = [obj1, obj2, obj3].reduce(<span class="hljs-function">(<span class="hljs-params">acc, curr</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> { ...acc, ...curr };
}, {});
<span class="hljs-built_in">console</span>.log(mergedObj); <span class="hljs-comment">// { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }</span>
</code></pre>
<p>In this example, we have two arguments <code>acc</code> and <code>curr</code> in the callback function. The <code>acc</code> represents the current merged object that has been created so far, while the <code>curr</code> represents the current object being processed in the array.</p>
<p>The function uses the spread operator (<code>...</code>) to create a new object that combines the properties of the current merged object <code>acc</code> and the current object <code>curr</code>. It then returns this new object.</p>
<p>In this case, the <code>reduce()</code> method will start by setting <code>acc</code> to an empty object (which is the value passed as the second argument to <code>reduce()</code>). It will then set <code>curr</code> to <code>obj1</code>, and create a new object that combines the properties of the empty object and <code>obj1</code>. It will then set <code>curr</code> to <code>obj2</code> and create a new object that combines the properties of the previous merged object and <code>obj2</code>. It will continue this process until it has processed all the objects in the array.</p>
<p>The final value of <code>acc</code> will be the merged object, which will contain all the properties of the original objects.</p>
<p><strong>Example 4</strong>: Using <code>reduce()</code> to group objects in an array. For example, grouping products in a shopping cart according to their brand name.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> shoppingCart = [
    {<span class="hljs-attr">name</span>: <span class="hljs-string">'Apple'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">1.99</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">3</span>},
    {<span class="hljs-attr">name</span>: <span class="hljs-string">'Apple'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">1.99</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">3</span>},
    {<span class="hljs-attr">name</span>: <span class="hljs-string">'Xiomi'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">2.99</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">2</span>},
    {<span class="hljs-attr">name</span>: <span class="hljs-string">'Samsung'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">3.99</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span>},
    {<span class="hljs-attr">name</span>: <span class="hljs-string">'Tesla'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">3.99</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span>},
    {<span class="hljs-attr">name</span>: <span class="hljs-string">'Tesla'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">4.99</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">4</span>},
    {<span class="hljs-attr">name</span>: <span class="hljs-string">'Nokia'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">4.99</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">4</span>},
]

<span class="hljs-keyword">const</span> products = shoppingCart.reduce(<span class="hljs-function">(<span class="hljs-params">productGroup, product</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> name = product.name;
    <span class="hljs-keyword">if</span>(productGroup[name] == <span class="hljs-literal">null</span>) {
        productGroup[name] = [];
    }
    productGroup[name].push(product);

    <span class="hljs-keyword">return</span> productGroup;
}, {});

<span class="hljs-built_in">console</span>.log(products);
</code></pre>
<pre><code class="lang-json"><span class="hljs-comment">// OUTPUT</span>
{
  Apple: [
    { name: 'Apple', price: <span class="hljs-number">1.99</span>, quantity: <span class="hljs-number">3</span> },
    { name: 'Apple', price: <span class="hljs-number">1.99</span>, quantity: <span class="hljs-number">3</span> }
  ],
  Xiomi: [ { name: 'Xiomi', price: <span class="hljs-number">2.99</span>, quantity: <span class="hljs-number">2</span> } ],
  Samsung: [ { name: 'Samsung', price: <span class="hljs-number">3.99</span>, quantity: <span class="hljs-number">1</span> } ],
  Tesla: [
    { name: 'Tesla', price: <span class="hljs-number">3.99</span>, quantity: <span class="hljs-number">1</span> },
    { name: 'Tesla', price: <span class="hljs-number">4.99</span>, quantity: <span class="hljs-number">4</span> }
  ],
  Nokia: [ { name: 'Nokia', price: <span class="hljs-number">4.99</span>, quantity: <span class="hljs-number">4</span> } ]
}
</code></pre>
<p>In this example, we have <code>shoppingCart</code> array representing different products and two arguments <code>productGroup</code> and <code>product</code> in the callback function.</p>
<p>The <code>productGroup</code> argument represents the current group of products that have been found so far, while the <code>product</code> argument represents the current product being processed in the array.</p>
<p>The function first gets the name of the current product using <code>product.name</code>. It then checks if there is already a group for this product name in the <code>productGroup</code> object using the <code>if</code> statement. If there is not, it creates a new group by initializing the <code>productGroup[name]</code> property to an empty array.</p>
<p>Finally, the function pushes the current product into the group using the <code>push()</code> method, and returns the updated <code>productGroup</code> object.</p>
<p>After the <code>reduce()</code> method has processed all the elements in the <code>shoppingCart</code> array, the resulting <code>productGroup</code> object will contain keys for each product name, and values that are arrays of products with that name.</p>
<h2 id="heading-benefits-of-higher-order-functions">Benefits of Higher Order Functions</h2>
<p>Using higher order functions has some important benefits for web developers.</p>
<p>First, higher order functions can help improve the legibility of your code by making it more concise and easy to understand. This can help speed up the development process and make it easier to debug code.</p>
<p>Second, higher order functions can help organize your code into smaller chunks, making it easier to maintain and extend.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article explored what a higher order function is, the benefits of using them, and how to use them in practical applications.</p>
<p>By using higher order functions, web developers can work smarter by organizing their code into smaller chunks and making it more legible and easier to debug.</p>
<p>Now, whenever you try to use map(), filter() and reduce() methods and get confused, just remember the following:</p>
<ul>
<li><p>Use map when you want to transform an array</p>
</li>
<li><p>Use filter to select a subset of data from an array, and</p>
</li>
<li><p>Use reduce when you want to return a single value as a result.</p>
</li>
</ul>
<p>For further reading on higher order functions, check out this awesome video by Akshay Saini on <a target="_blank" href="https://www.youtube.com/watch?v=HkWxvB1RJq0">YouTube</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
