<?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[ Furkan Emin Can - 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[ Furkan Emin Can - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 21 May 2026 10:20:50 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/femincan/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Get the First Line of a Multiline String in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, getting the first element of an array or string is pretty easy. But when it comes to getting the first line of a multiline string, some approaches can hurt your app's performance in certain cases. In this article, we will look at the t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-the-first-line-of-a-multiline-string-in-javascript/</link>
                <guid isPermaLink="false">66ba122d63860a72fccae75e</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Furkan Emin Can ]]>
                </dc:creator>
                <pubDate>Wed, 24 Jan 2024 23:33:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, getting the first element of an array or string is pretty easy. But when it comes to getting the first line of a multiline string, some approaches can hurt your app's performance in certain cases.</p>
<p>In this article, we will look at the three best ways you can get the first line of a multiline string in JS. </p>
<p>For those of you in a hurry, here is the best solution:</p>
<pre><code class="lang-javascript">input.slice(<span class="hljs-number">0</span>, input.indexOf(<span class="hljs-string">"\n"</span>));
</code></pre>
<p>And now if you want to learn more, let's dive deep into the details.</p>
<h2 id="heading-the-problem">The Problem</h2>
<p>The main problem in most solutions is that, in order to simply get the first line of the string, you have to operate over the entire string. If the input is too big, this operation takes an unnecessarily long time and consumes many resources.</p>
<p>Let's explain with an example.</p>
<p>Let's say, I have a gigantic string that contains 10 million lines of text and I want to get the first line of it. So I choose to use the <code>Array.split</code> method like in the following example:</p>
<pre><code class="lang-javascript">input.split(<span class="hljs-string">"\n"</span>)[<span class="hljs-number">0</span>];
</code></pre>
<p>In this code, the <code>split</code> method operates over the entire 10 million lines to get only the first line. As a result, to get only the first item, I have an array containing 10 million items.</p>
<p>This operation takes approximately <code>1.7</code> seconds on my PC. This is unnecessarily long for such a small operation.</p>
<p>Let's look at the solutions to overcome this problem.</p>
<h2 id="heading-the-solutions">The Solutions</h2>
<p>After some research, I found the three best ways of doing this operation:</p>
<ol>
<li>Using the <code>String.indexOf</code> and <code>String.slice</code> methods.</li>
<li>Using the <code>Array.split</code> method.</li>
<li>Using the <code>String.match</code> method.</li>
</ol>
<p>Here are the benchmark results of each solution:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/benchmarks.png" alt="Image" width="600" height="400" loading="lazy">
<em>Benchmark results</em></p>
<p>Also, you can access the benchmark results from <a target="_blank" href="https://perf.link/#eyJpZCI6InhzeG9lOGh6cDgzIiwidGl0bGUiOiJHZXR0aW5nIHRoZSBmaXJzdCBsaW5lIG9mIGEgbXVsdGlsaW5lIHN0cmluZyIsImJlZm9yZSI6ImNvbnN0IGlucHV0ID0gQXJyYXkuZnJvbShBcnJheSgxMDAwKSwgKF8sIGkpID0%2BIGBJIGFtIHRoZSBsaW5lICR7aSArIDF9YCkuam9pbignXFxuJyk7IiwidGVzdHMiOlt7Im5hbWUiOiJTdHJpbmcuc2xpY2Ug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IwMDAsMzQzODAwMCw1MzQwMDAsNDA2MzAwMCwyNTYwMDAsMTQ4MjAwMCwyMjMwMDAwLDgxODAwMCw0MTAwMCw0NTMwMDAsMjAwMDAsMjI2NDAwMCwyODkwMDAwLDc2NzAwMCwyNDE2MDAwLDE3MzEwMDAsMTk0MDAwMCwzMTU3MDAwLDI3NzgwMDAsMTY2MzAwMCw3MDUwMDAsMzEyNTAwMCwxODE5MDAwLDIwMTEwMDAsMTQ0MDAwMCw3NDcwMDAsMTAwMCwxMzAwMDAwLDEzMDIwMDAsMjI0ODAwMCw1MDYwMDAsMTMwMjAwMF0sIm9wcyI6MTcyODM2MH1dLCJ1cGRhdGVkIjoiMjAyNC0wMS0yMlQxOTowNDoxMS4zMzRaIn0%3D">this link</a> and perform benchmarks yourself, too.</p>
<p>Let's explore each solution separately.</p>
<h3 id="heading-1-using-the-stringindexof-and-stringslice-methods">1. Using the <code>String.indexOf</code> and <code>String.slice</code> Methods</h3>
<p>In this solution, we will use the <code>String.indexOf</code> method to find the index of the new line (<code>\n</code>) character, and then will slice the string to this index with the <code>String.slice</code> method.</p>
<pre><code class="lang-javascript">input.slice(<span class="hljs-number">0</span>, input.indexOf(<span class="hljs-string">"\n"</span>));
</code></pre>
<p>This solution takes first place in the benchmark results.</p>
<h3 id="heading-2-using-the-arraysplit-method">2. Using the <code>Array.split</code> Method</h3>
<p>As you have seen in the problem, the <code>Array.split</code> method operates over the entire string. But it also accepts an optional <code>limit</code> parameter. We can leverage this parameter to avoid unnecessary operations.</p>
<pre><code class="lang-javascript">input.split(<span class="hljs-string">"\n"</span>, <span class="hljs-number">1</span>)[<span class="hljs-number">0</span>];
</code></pre>
<p>In this code, we took advantage of the optional <code>limit</code> parameter and so the operation stops after the first split operation.</p>
<p>This solution takes second place in the benchmark results.</p>
<h3 id="heading-3-using-the-stringmatch-method">3. Using the <code>String.match</code> Method</h3>
<p>This approach is for those of you who particularly want to use regex.</p>
<p>We will use the <code>String.match</code> method in this case. We will create a regex literal that matches with any character group which is followed by a new line character, and pass it to the method. The first element of the returned array (which is the match) is the first line.</p>
<pre><code class="lang-javascript">input.match(<span class="hljs-regexp">/.*(?=\n)/</span>)[<span class="hljs-number">0</span>];
</code></pre>
<p>This solution takes third place in the benchmark results and performs two times slower than the first solution.</p>
<p>According to <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#literal_notation_and_constructor">the MDN</a>:</p>
<blockquote>
<p>Before regular expressions can be used, they have to be compiled.</p>
</blockquote>
<p>The performance downgrade is probably because of that.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we have looked at three different approaches to get the first line of a multiline string.</p>
<p>As developers, even for such a small operation, we should consider edge cases to avoid potential problems in the future.</p>
<p>Thank you for reading. You can connect with me on <a target="_blank" href="https://twitter.com/femincan">Twitter</a> or explore more on <a target="_blank" href="https://femincan.dev">my personal blog</a>. Feel free to reach out — I'd love to hear from you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use the SWR Library for Better Data Fetching in React ]]>
                </title>
                <description>
                    <![CDATA[ React is un-opinionated about how you fetch and manage the remote data in your application. You may think of using the useEffect hook for simple fetching operations, but it will not help you with caching, request deduplication, always serving real-ti... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/swr-library-for-data-fetching-in-react/</link>
                <guid isPermaLink="false">66ba12309065919bb4e84cba</guid>
                
                    <category>
                        <![CDATA[ hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Furkan Emin Can ]]>
                </dc:creator>
                <pubDate>Tue, 05 Dec 2023 21:59:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React is un-opinionated about how you fetch and manage the remote data in your application.</p>
<p>You may think of using the <code>useEffect</code> hook for simple fetching operations, but it will not help you with caching, request deduplication, always serving real-time data, and so on.</p>
<p>Things will get more complicated when you try to implement them by yourself. But fortunately, the SWR library helps us solve some common problems and it also simplifies development.</p>
<h2 id="heading-what-is-the-swr-library">What is the SWR Library?</h2>
<p>According to the <a target="_blank" href="https://swr.vercel.app">SWR documentation</a>:</p>
<blockquote>
<p>The name “SWR” is derived from <code>stale-while-revalidate</code>, a HTTP cache invalidation strategy popularized by <a target="_blank" href="https://tools.ietf.org/html/rfc5861">HTTP RFC 5861</a>.   </p>
<p>SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.</p>
</blockquote>
<p>With the help of this strategy, you can make sure to always display up-to-date data to your users.</p>
<p>So, SWR is a library built upon the <code>stale-while-revalidate</code> strategy, and it provides React hooks for data fetching.</p>
<p>Before moving on to the details, let's look at the two most important concepts of SWR.</p>
<h3 id="heading-caching">Caching</h3>
<p>A cache stores data for a specified amount of time and serves this data to users who request it within that period of time.</p>
<p>The time can be a certain period like <code>5000ms</code> or can be an event like re-connecting to the Internet.</p>
<p>SWR automatically caches the fetched data, helping to quickly serve the data without making redundant network requests.</p>
<h3 id="heading-revalidation">Revalidation</h3>
<p>When the valid time is exceeded, the data becomes stale. When a user requests this data you should revalidate it before serving it.</p>
<p>If the data is stale, SWR revalidates it (re-fetches from the server) to keep it fresh.</p>
<p>By default, SWR automatically revalidates the data (it assumes that the data is stale) in three cases:</p>
<ol>
<li>Every time the component is mounted, even if there is data in the cache, it revalidates.</li>
<li>It revalidates when the window gets focused.</li>
<li>It revalidates when the browser regains its network connection.</li>
</ol>
<h2 id="heading-how-to-use-the-useswr-hook">How to Use the <code>useSWR</code> Hook</h2>
<p>The <code>useSWR</code> hook is the main hook of the library. In your projects, you'll almost always use this hook.</p>
<p>It accepts three parameters: <code>key</code>, <code>fetcher</code>, and <code>options</code>.</p>
<ul>
<li><code>key</code> is a unique string for the request like an id.</li>
<li><code>fetcher</code> is an async function that accepts the <code>key</code> and returns the <code>data</code>. SWR automatically passes the <code>key</code> to the <code>fetcher</code> function when loading the data.</li>
<li><code>options</code> is an object of options available for the hook. For example, you can specify the cache time in the <code>options</code> object.</li>
</ul>
<p>And it returns an object with <code>data</code>, <code>error</code>, <code>isValidating</code>, <code>isLoading</code>, and <code>mutate</code> properties.</p>
<ul>
<li><code>data</code> is the variable returned from the <code>fetcher</code> function. During the first request, it will be <code>undefined</code>.</li>
<li><code>error</code> is the error thrown by the <code>fetcher</code> function. If there is no error, it will be <code>undefined</code>.</li>
<li><code>isLoading</code> is a boolean that indicates the <strong>first</strong> request's status. It is <code>true</code> during the first request, and it will always be <code>false</code> thereafter.</li>
<li><code>isValidating</code> is also a boolean that indicates the request's status. It is <code>true</code> during each request including the first one.</li>
<li><code>mutate</code> is a function for manually triggering a revalidation.</li>
</ul>
<h2 id="heading-how-i-used-swr-in-my-project">How I Used SWR in My Project</h2>
<p>The best thing about SWR is how easy it is to use. I tried out it in my first project for the <a target="_blank" href="https://www.freecodecamp.org/learn/front-end-development-libraries">Front End Libraries Certification</a> of freeCodeCamp and liked it very much.</p>
<p>I used TypeScript for the project, but will give you examples with JavaScript. So, don't worry if you don't know TypeScript – I highly recommend giving it a try if you haven't yet.</p>
<p>Also, if you are interested, you can find the project's code in its <a target="_blank" href="https://github.com/femincan/quote-factory">GitHub repository</a>.</p>
<h3 id="heading-how-to-add-the-swr-dependency-to-the-project">How to Add the <code>swr</code> Dependency to the Project</h3>
<p>To be able to use the library, you can install it via <code>npm</code>, <code>pnpm</code>, or <code>yarn</code>. I prefer using <code>pnpm</code> as the package manager for my project.</p>
<pre><code class="lang-bash">$ npm i swr
<span class="hljs-comment"># or</span>
$ pnpm add swr
<span class="hljs-comment"># or</span>
$ yarn add swr
</code></pre>
<h3 id="heading-create-the-fetcher-function">Create the <code>fetcher</code> Function</h3>
<p>The goal of this function is to fetch the data by URL and return it. I will use the function with SWR.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetcher = <span class="hljs-keyword">async</span> (url) =&gt; {
  <span class="hljs-keyword">const</span> { data } = <span class="hljs-keyword">await</span> axios.get(url);

  <span class="hljs-keyword">return</span> data;
};
</code></pre>
<p>The <code>fetcher</code> function:</p>
<ul>
<li>accepts a <code>url</code> parameter,</li>
<li>fetches the data with the <code>get</code> method of Axios,</li>
<li>returns the <code>data</code> returned from the request.</li>
</ul>
<h3 id="heading-create-a-hook-that-fetches-a-random-quote">Create a Hook That Fetches a Random Quote</h3>
<p>Based on the <a target="_blank" href="https://swr.vercel.app/docs/getting-started#make-it-reusable">SWR documentation</a>, I created a hook called <code>useRandomQuote</code>. This hook is a wrapper for the <code>useSWR</code> hook. Thus, I can use the same data wherever needed.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> useSWR <span class="hljs-keyword">from</span> <span class="hljs-string">'swr/immutable'</span>;

<span class="hljs-keyword">const</span> useRandomQuote = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { data, ...restSWR } = useSWR(
    <span class="hljs-string">'https://api.quotable.io/quotes/random'</span>,
    fetcher
  );

  <span class="hljs-keyword">return</span> {
    ...restSWR,
    <span class="hljs-attr">quote</span>: data?.[<span class="hljs-number">0</span>],
  };
};

<span class="hljs-keyword">export</span> { useRandomQuote };
</code></pre>
<p>The hook fetches the data with <code>useSWR</code> and returns an object that contains the variables destructured from the <code>useSWR</code> hook and the <code>quote</code> property which is the only element in the returned array. I used the Quotable API for a random quote, and the API returns an array with one element which is the random quote.</p>
<p>If you noticed, I imported the <code>useSWR</code> hook from <code>swr/immutable</code> in the code snippet. It is auto-revalidation disabled version of the hook. I prefer to use it because I want to revalidate the data manually with the <code>mutate</code> function.</p>
<h3 id="heading-how-to-revalidate-the-data-manually">How to Revalidate the Data Manually</h3>
<p>If you want to manually revalidate the data, you can use the <code>mutate</code> function returned from the <code>useSWR</code> hook.</p>
<p>When the mutate function is called, SWR revalidates the data. During this process, the <code>data</code> variable remains the same (will not be undefined), and the <code>isValidating</code> variable becomes true.</p>
<p>The following diagram from the <a target="_blank" href="https://swr.vercel.app/docs/advanced/understanding#fetch-and-revalidate">SWR documentation</a> visualizes the revalidation process:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/fetch-and-revalidate-pattern.png" alt="A diagram for the &quot;Fetch and Revalidate&quot; pattern in SWR" width="600" height="400" loading="lazy">
<em>A diagram for the "Fetch and Revalidate" pattern in SWR</em></p>
<p>In my project, I have a <code>QuoteCard</code> component that displays the current quote. This component has a <code>New Quote</code> button that triggers retrieving a new random quote.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> QuoteCard = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { <span class="hljs-comment">/* ... */</span>, mutate } = useRandomQuote();

  <span class="hljs-keyword">return</span> (
    {<span class="hljs-comment">/* ... */</span>}
    &lt;button
      <span class="hljs-comment">// ...</span>
      onClick={<span class="hljs-function">() =&gt;</span> mutate()}
    &gt;
      New Quote
    &lt;/button&gt;
    {<span class="hljs-comment">/* ... */</span>}
  )
}
</code></pre>
<p>In the code above, I used the <code>mutate</code> function in the <code>onClick</code> handler of the <code>New Quote</code> button.</p>
<h3 id="heading-how-to-handle-concurrent-requests">How to Handle Concurrent Requests</h3>
<p>If the user initiates a new request alongside the ongoing one, this results in multiple concurrent requests. Each request waits for the previous one to complete before starting the process, resulting in unnecessary network usage and waiting time.</p>
<p>I faced the same issue in my project. When the user clicks the <code>New Quote</code> button while a request is still loading, the application triggers a new request alongside the existing one.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/illustration.gif" alt="Concurrent requests that being triggered by clicking the &quot;New Quote&quot; button continuously" width="600" height="400" loading="lazy">
<em>Concurrent requests that being triggered by clicking the "New Quote" button continuously</em></p>
<p>As you see in the GIF above, when I click the "New Quote" button consecutively, I have to wait for all requests to be done to see a random quote because SWR only updates the data after the last request is completed.</p>
<p>As a result, I should cancel the ongoing previous request after a new request is initiated. Although I checked SWR's documentation, I couldn't find a built-in solution for this issue. I tried to use <code>AbortController</code> with SWR, but couldn't succeed.</p>
<p>As a workaround, I disabled the <code>New Quote</code> button during validation to be able to prevent multiple concurrent requests.</p>
<p>A little note: I also checked <a target="_blank" href="https://tanstack.com/query/latest">React Query</a>, and it has a built-in solution for that. I am planning to experiment with it in my next project involving remote data.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>React doesn't care how you fetch and manage remote data. In this tutorial, you have learned how to do this with SWR. Although it has a big drawback regarding canceling concurrent requests, you can usually work around this and benefit from its upsides.</p>
<p>If you haven't used SWR before, I highly recommend trying it out in your future projects. It saves you time and prevents you from experiencing many types of bugs.</p>
<p>Thank you for reading. You can connect with me on <a target="_blank" href="https://twitter.com/femincan">Twitter</a> or explore more on <a target="_blank" href="https://femincan.dev">my personal website</a>. Feel free to reach out — I'd love to hear from you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Declare Variables in JavaScript – var, let, and const Explained ]]>
                </title>
                <description>
                    <![CDATA[ Declaring variables is something you'll do all the time in JavaScript. And if you know the variable declaration process inside and out, you'll have the confidence to start writing great JS code. Through this article, you will learn how to declare and... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-declare-variables-in-javascript/</link>
                <guid isPermaLink="false">66ba122a07d2a5882dd9930d</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Furkan Emin Can ]]>
                </dc:creator>
                <pubDate>Tue, 07 Nov 2023 22:16:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/Cover-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Declaring variables is something you'll do all the time in JavaScript. And if you know the variable declaration process inside and out, you'll have the confidence to start writing great JS code.</p>
<p>Through this article, you will learn how to declare and mutate variables using <code>var</code>, <code>let</code>, and <code>const</code>, and you'll get a better understanding of the differences between them.</p>
<p>I will explain each concept in two parts:</p>
<ul>
<li>Before ES6 (<code>var</code> statement)</li>
<li>After ES6 (<code>let</code> and <code>const</code> statements)</li>
</ul>
<p>Let's dive into these different ways of declaring variables in JavaScript so you know how they work and when to use each one.</p>
<h2 id="heading-how-to-declare-variables-in-javascript">How to Declare Variables in JavaScript</h2>
<p>When you declare variables in your app, the interpreter moves them to the top of their scope and allocates places in the memory before the execution starts. This process is called <strong>Hoisting</strong>.</p>
<h3 id="heading-1-how-to-declare-variables-with-var-in-javascript">1. How to declare variables with <code>var</code> in JavaScript:</h3>
<p>When you declare a variable with <code>var</code>, it is hoisted and initialized in the memory as <code>undefined</code> before the code execution. So, you can access the variable before declaring it, but it returns <code>undefined</code>. This is sometimes called <strong>Declaration hoisting</strong>.</p>
<p>When the execution starts and reaches the line where the variable is declared, it replaces the value in memory with the value of the variable.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(strawberry); <span class="hljs-comment">// undefined</span>

<span class="hljs-keyword">var</span> strawberry = <span class="hljs-string">'🍓'</span>;

<span class="hljs-built_in">console</span>.log(strawberry); <span class="hljs-comment">// 🍓</span>
</code></pre>
<p>Under the hood, the code above behaves like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> strawberry;

<span class="hljs-built_in">console</span>.log(strawberry); <span class="hljs-comment">// undefined</span>

strawberry = <span class="hljs-string">'🍓'</span>;

<span class="hljs-built_in">console</span>.log(strawberry); <span class="hljs-comment">// 🍓</span>
</code></pre>
<p>So we can use the <code>strawberry</code> variable before the declaration, but it returns <code>undefined</code>.</p>
<p>With this behavior, the program runs without errors. But in some cases, this can lead to unexpected results. We are only human, and on a busy day you might try to access a variable before declaring it. In a complex program, it can be hard to figure out where a strange <code>undefined</code> comes from.</p>
<h3 id="heading-2-how-to-declare-variables-with-let-and-const-in-javascript">2. How to declare variables with <code>let</code> and <code>const</code> in JavaScript:</h3>
<p>When you declare a variable with <code>let</code> or <code>const</code>, it is also hoisted but it's allocated in the memory as <strong>uninitialized</strong> in the <a target="_blank" href="https://www.freecodecamp.org/news/what-is-the-temporal-dead-zone/">temporal dead zone</a>. You cannot access variables in the temporal dead zone before you've declared them. So, if you try to access a variable before declaring it, the program throws a <code>ReferenceError</code>.</p>
<p>When the program reaches the line where the variable is declared, it initializes it with that value.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(cherry); <span class="hljs-comment">// ReferenceError</span>

<span class="hljs-keyword">const</span> cherry = <span class="hljs-string">"🍒"</span>;

<span class="hljs-built_in">console</span>.log(cherry); <span class="hljs-comment">// 🍒</span>
</code></pre>
<p>If you try to run this code snippet, you will see an error similar to the following one because we tried to access a variable in the temporal dead zone. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/error-1.png" alt="ReferenceError: Cannot access 'cherry' before initialization" width="600" height="400" loading="lazy">
<em>"ReferenceError: Cannot access 'cherry' before initialization"</em></p>
<p>This is a more predictable behavior than the behavior of the <code>var</code> statement.</p>
<h3 id="heading-so-what-do-var-let-and-const-have-in-common">So what do <code>var</code>, <code>let</code>, and <code>const</code> have in common?</h3>
<p>In the previous two sections, you learned the process for declaring <code>var</code>, <code>let</code>, and <code>const</code>. In this section, we will look at the common concepts.</p>
<ul>
<li>You can declare a variable with <code>let</code> and <code>var</code> without a value. In this case, the default value will be <code>undefined</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> tomato;
<span class="hljs-keyword">let</span> potato;

<span class="hljs-built_in">console</span>.log(tomato); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(potato); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>This behavior is not valid for <code>const</code> because an initial value is required for it. If there is no initial value, the program throws a <code>SyntaxError</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> avocado; <span class="hljs-comment">// SyntaxError</span>
</code></pre>
<p>For the code above, an error gets thrown  like this one:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/image-4.png" alt="&quot;SyntaxError: Missing initializer in const declaration&quot;" width="600" height="400" loading="lazy">
<em>SyntaxError: Missing initializer in const declaration</em></p>
<ul>
<li>You can declare a chain of variables using the same statement. Put the statement at the beginning and separate each variable with a comma. This is valid for <code>var</code>, <code>let</code>, and <code>const</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> number1 = <span class="hljs-number">2</span>, number2 = <span class="hljs-number">23</span>, number3 = <span class="hljs-number">99</span>;

<span class="hljs-built_in">console</span>.log(number1); <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(number2); <span class="hljs-comment">// 23</span>
<span class="hljs-built_in">console</span>.log(number3); <span class="hljs-comment">// 99</span>
</code></pre>
<p>Nowadays, to declare variables, you'll want to use the ES6 statements <code>let</code> and <code>const</code>. You can think of <code>var</code> as the legacy method of doing this.</p>
<p>My recommendation is:</p>
<ul>
<li>Use <code>const</code> as the default.</li>
<li>Use <code>let</code> if the variable will change in the future.</li>
<li>Don't use <code>var</code> if there is no particular use case.</li>
</ul>
<h2 id="heading-javascript-variables-and-scope">JavaScript Variables and Scope</h2>
<p>According to <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Scope">MDN</a>:</p>
<blockquote>
<p>The <strong>scope</strong> is the current context of execution in which values and expressions are "visible" or can be referenced.</p>
</blockquote>
<p>In terms of variables, the scope is where certain variables are available. We can access variables that have been declared in a parent scope in a child scope, but it doesn't work the other way around.</p>
<h3 id="heading-global-scope">Global Scope</h3>
<p><strong>Global Scope</strong> is the main scope that covers all the scopes in a script. Variables declared in the global scope are available in all scopes.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>

<span class="hljs-keyword">const</span> grapes = <span class="hljs-string">"🍇"</span>;

<span class="hljs-comment">// Functional Scope</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logGrapes</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(grapes); <span class="hljs-comment">// 🍇</span>

  <span class="hljs-comment">// Block Scope in a Functional Scope</span>
  {
    <span class="hljs-built_in">console</span>.log(grapes); <span class="hljs-comment">// 🍇</span>
  }
}

<span class="hljs-comment">// Block Scope</span>
{
  <span class="hljs-built_in">console</span>.log(grapes); <span class="hljs-comment">// 🍇</span>
}
</code></pre>
<p>In the example above, we can access the <code>grapes</code> variable from all child scopes because it is declared in the global scope.</p>
<h3 id="heading-functional-scope">Functional Scope</h3>
<p><strong>Functional scope</strong> is the scope created with a function declaration. Variables declared in a functional scope are only available in that scope and cannot be accessed outside of it. The behavior of <code>var</code>, <code>let</code>, and <code>const</code> are the same in this case. </p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>

<span class="hljs-comment">// Functional Scope</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createVariables</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> apple = <span class="hljs-string">"🍎"</span>;
  <span class="hljs-keyword">const</span> cherry = <span class="hljs-string">"🍒"</span>;
  <span class="hljs-keyword">let</span> strawberry = <span class="hljs-string">"🍓"</span>;
}

<span class="hljs-built_in">console</span>.log(apple); <span class="hljs-comment">// ReferenceError</span>
<span class="hljs-built_in">console</span>.log(cherry); <span class="hljs-comment">// ReferenceError</span>
<span class="hljs-built_in">console</span>.log(strawberry); <span class="hljs-comment">// ReferenceError</span>
</code></pre>
<p>In the example above, all three variables are only accessible in the functional scope of the <code>createVariables</code> function. If you try to access them outside of the functional scope the program throws a <code>ReferenceError</code>.</p>
<h3 id="heading-block-scope">Block Scope</h3>
<p><strong>Block scope</strong> is the scope that is created with a pair of curly braces. Block scope is only valid for <code>let</code> and <code>const</code>, not <code>var</code>. When you declare a variable with <code>var</code> it is moved to the global scope or the nearest functional scope if it exists.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Block Scope</span>
{
  <span class="hljs-keyword">const</span> banana = <span class="hljs-string">"🍌"</span>;

  <span class="hljs-comment">// Block Scope in a Block Scope</span>
  {
    <span class="hljs-built_in">console</span>.log(banana); <span class="hljs-comment">// 🍌</span>

    <span class="hljs-keyword">var</span> carrot = <span class="hljs-string">"🥕"</span>;
    <span class="hljs-keyword">let</span> lemon = <span class="hljs-string">"🍋"</span>;
  }

  <span class="hljs-built_in">console</span>.log(carrot); <span class="hljs-comment">// 🥕</span>
  <span class="hljs-built_in">console</span>.log(lemon); <span class="hljs-comment">// ReferenceError</span>
}
</code></pre>
<p>In the example above:</p>
<ul>
<li>We can access the <code>banana</code> variable that we declared with <code>const</code> in the parent scope in the child scope.</li>
<li>We can access the <code>carrot</code> variable declared with <code>var</code> in the child scope in the parent scope because the program moves it to the global scope.</li>
<li>We can't access the <code>lemon</code> variable declared with <code>let</code> in the child scope in the parent scope because it cannot be accessed outside of the scope in which it's declared. If try to do that, the program throws a <code>ReferenceError</code>.</li>
</ul>
<h2 id="heading-how-to-mutate-variables-in-javascript">How to Mutate Variables in JavaScript</h2>
<p>In this section, we'll talk about the <code>var</code> and <code>let</code> statements together, and then discuss how the <code>const</code> statement behaves. This is because the variables declared with <code>var</code> and <code>let</code> are mutable (that is, they can be changed), while variables declared with <code>const</code> are immutable.</p>
<h3 id="heading-1-mutation-in-var-and-let-statements">1. Mutation in <code>var</code> and <code>let</code> statements</h3>
<p>As I said, the variables declared with <code>var</code> and <code>let</code> are mutable, which means that you can assign new values to them. Here's what I mean:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> pepper = <span class="hljs-string">"🌶️"</span>;
<span class="hljs-keyword">let</span> apple = <span class="hljs-string">"🍏"</span>;

pepper = <span class="hljs-string">"🫑"</span>;
apple = <span class="hljs-string">"🍎"</span>;

<span class="hljs-built_in">console</span>.log(pepper); <span class="hljs-comment">// 🫑</span>
<span class="hljs-built_in">console</span>.log(apple); <span class="hljs-comment">// 🍎</span>
</code></pre>
<p>In the example above, we mutated the <code>pepper</code> and <code>apple</code> variables, and they were assigned new values.</p>
<h3 id="heading-2-mutation-in-const-statement">2. Mutation in <code>const</code> statement</h3>
<p>Variables declared with <code>const</code> are immutable. So you cannot assign new values to them once you've declared them.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> strawberry = <span class="hljs-string">"🍓"</span>;

strawberry = <span class="hljs-string">"🍉"</span>; <span class="hljs-comment">// TypeError</span>
</code></pre>
<p>If you try to run the code snippet above, the program throws an error like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/error-3.png" alt="TypeError: Assignment to constant variable." width="600" height="400" loading="lazy">
<em>"TypeError: Assignment to constant variable."</em></p>
<p>Objects are an exception for the immutability of the <code>const</code> statement because they have properties and methods, unlike <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">primitives</a>.</p>
<p>You cannot mutate them via assignment but can mutate them via their methods and property assignment. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = [<span class="hljs-string">"🍎"</span>, <span class="hljs-string">"🍐"</span>];
<span class="hljs-keyword">const</span> fruitEmojiMap = {
  <span class="hljs-attr">apple</span>: <span class="hljs-string">"🍎"</span>,
  <span class="hljs-attr">pear</span>: <span class="hljs-string">"🍐"</span>,
};

fruits[<span class="hljs-number">2</span>] = <span class="hljs-string">"🍒"</span>; <span class="hljs-comment">// [ '🍎', '🍐', '🍒' ]</span>
fruits.push(<span class="hljs-string">"🍌"</span>); <span class="hljs-comment">// [ '🍎', '🍐', '🍒', '🍌' ]</span>

fruitEmojiMap.cherry = <span class="hljs-string">"🍒"</span>; <span class="hljs-comment">// { apple: '🍎', pear: '🍐', cherry: '🍒' }</span>
</code></pre>
<p>In the code example above,</p>
<ul>
<li>We added two new fruits to the <code>fruits</code> array via property assignment, and used the <code>push</code> method of the <code>Array</code> object.</li>
<li>We added a new fruit to the <code>fruitEmojiMap</code> object via property assignment.</li>
</ul>
<p>A little note: you can use the <code>[Object.freeze()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)</code> method to achieve complete immutability for objects.</p>
<h2 id="heading-how-to-redeclare-variables-in-javascript">How to Redeclare Variables in JavaScript</h2>
<p>Redeclaring a variable with the same name in the same scope is likely something you don't want to do intentionally, and I've never found a real use case for it.</p>
<p>But strangely, we can redeclare variables declared with <code>var</code> using the same name in the same scope. This is another error-prone characteristic of the <code>var</code> statement. Fortunately, this behavior was changed with the <code>let</code> and <code>const</code> statements.</p>
<h3 id="heading-1-how-to-redeclare-variables-with-var"><strong>1.</strong> How to redeclare variables with <code>var</code></h3>
<p>You can redeclare a variable declared with <code>var</code> in the same scope or child-parent scopes. The variable will be affected in the global scope, or functional scope if it is declared in a function.</p>
<p>So even if you redeclare a variable in the child scope, the variable will change in all scopes where that variable is available.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>
<span class="hljs-keyword">var</span> pepper = <span class="hljs-string">"🌶️"</span>;

<span class="hljs-built_in">console</span>.log(pepper); <span class="hljs-comment">// 🌶️</span>

<span class="hljs-comment">// Block Scope</span>
{
  <span class="hljs-keyword">var</span> pepper = <span class="hljs-string">"🥦"</span>;

  <span class="hljs-built_in">console</span>.log(pepper); <span class="hljs-comment">// 🥦</span>
}

<span class="hljs-built_in">console</span>.log(pepper); <span class="hljs-comment">// 🥦</span>
</code></pre>
<p>In the example above, we declared a new <code>pepper</code> variable in the block scope and assigned it a different value. This affects the variable in the global scope and we lose access to the previous variable.</p>
<p>This behavior tends to cause big problems. Because someone working in the same codebase may unintentionally declare a variable using the same name used before.</p>
<p>The process is a bit different if you make the redeclaration in a function. The variable outside of the function remains the same and the variable inside the function cannot affect it. As I said, variables declared with <code>var</code> in a function are in functional scope and don't affect the outside.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>
<span class="hljs-keyword">var</span> onion = <span class="hljs-string">"🧅"</span>;

<span class="hljs-comment">// Functional Scope</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">redeclareOnion</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> onion = <span class="hljs-string">"🧄"</span>;

  <span class="hljs-built_in">console</span>.log(onion); <span class="hljs-comment">// 🧄</span>
}

<span class="hljs-built_in">console</span>.log(onion); <span class="hljs-comment">// 🧅</span>
</code></pre>
<p>In the example above, even though we declared a new variable using the same name as the <code>onion</code> variable inside a function, the <code>onion</code> variable declared in the global scope remained the same.</p>
<h3 id="heading-2-how-to-redeclare-variables-with-let-and-const">2. How to redeclare variables with <code>let</code> and <code>const</code></h3>
<p>You cannot redeclare variables declared with <code>let</code> or <code>const</code> in the same scope. If you try to do so, the program throws a <code>SyntaxError</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> eggplant = <span class="hljs-string">"🍆"</span>;

<span class="hljs-keyword">let</span> eggplant = <span class="hljs-string">"🥔"</span>; <span class="hljs-comment">// SyntaxError</span>
</code></pre>
<p>In the example above, we tried to redeclare the <code>eggplant</code> variable in the same scope, and the program threw the following error:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/image-17.png" alt="SyntaxError: Identifier 'eggplant' has already been declared" width="600" height="400" loading="lazy">
<em>"SyntaxError: Identifier 'eggplant' has already been declared"</em></p>
<p>But you can redeclare variables using <code>let</code> and <code>const</code> in child scopes. Because the variables declared with <code>let</code> and <code>const</code> are block scope and don't affect the parent scopes.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>
<span class="hljs-keyword">const</span> carrot = <span class="hljs-string">"🥕"</span>;

<span class="hljs-comment">// Block Scope</span>
{
  <span class="hljs-keyword">const</span> carrot = <span class="hljs-string">"🍒"</span>;

  <span class="hljs-built_in">console</span>.log(carrot); <span class="hljs-comment">// 🍒</span>
}

<span class="hljs-built_in">console</span>.log(carrot); <span class="hljs-comment">// 🥕</span>
</code></pre>
<p>In the example above, we declared two <code>carrot</code> variables. The first one is in the global scope and the second one is in the block scope with a different value. The variable in the global scope remains the same and the variable in the block scope is a standalone new variable.</p>
<p>The downside is that we lost access to the <code>carrot</code> variable declared in the global scope, in the block scope. If we need this variable in the future we can't access the variable.</p>
<p>So, most of the time, it is better to declare a variable with a unique name.</p>
<h3 id="heading-3-how-to-redeclare-variables-by-mixing-statements">3. How to Redeclare Variables by Mixing Statements</h3>
<p>Briefly, you shouldn't mix statements. This section is intended to give you information rather than really show you how the process is done.</p>
<p>You cannot create variables by mixing statements using the same name in the same scope. If you try it, the program throws a <code>SyntaxError</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> banana = <span class="hljs-string">"🍌"</span>;

<span class="hljs-keyword">var</span> banana = <span class="hljs-string">"🍋"</span>; <span class="hljs-comment">// SyntaxError</span>
</code></pre>
<p>In the example above, we tried to redeclare the <code>banana</code> variable declared with <code>const</code> with <code>var</code>, but the program threw an error similar to the one below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/image-16.png" alt="SyntaxError: Identifier 'banana' has already been declared" width="600" height="400" loading="lazy">
<em>"SyntaxError: Identifier 'banana' has already been declared"</em></p>
<p>Also, you cannot declare a variable with <code>var</code> using the same name as one already declared in a parent scope using <code>let</code> or <code>const</code>. As I said, <code>var</code> is global scope and affects the variable declared in parent scopes unless it is inside a function.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>
<span class="hljs-keyword">let</span> pineapple = <span class="hljs-string">"🍍"</span>;

<span class="hljs-comment">// Functional Scope</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">declarePineapple</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> pineapple = <span class="hljs-string">"🍏"</span>; <span class="hljs-comment">// This is okay</span>
}

<span class="hljs-comment">// Block Scope</span>
{
  <span class="hljs-keyword">var</span> pineapple = <span class="hljs-string">"🍎"</span>; <span class="hljs-comment">// SyntaxError</span>
}
</code></pre>
<p>In the example above, we tried to redeclare the <code>pineapple</code> variable in two places:</p>
<ul>
<li>In the function, which we did successfully.</li>
<li>But in the child block scope, the program threw the following error:</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/image-19.png" alt="SyntaxError: Identifier 'pineapple' has already been declared" width="600" height="400" loading="lazy">
<em>"SyntaxError: Identifier 'pineapple' has already been declared"</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>These days, <code>let</code> and <code>const</code> are the default choice for variable declaration in JavaScript. But you might still encounter the <code>var</code> statement, especially in older apps. So you'll need to know how to handle it.</p>
<p>In this guide, you have learned the differences between <code>var</code>, <code>let</code>, and <code>const</code>. We also talked about hoisting and scope in variable declaration.</p>
<p>See you in the next one!</p>
<h3 id="heading-stay-in-touch">Stay in Touch</h3>
<p>You can connect with me on <a target="_blank" href="https://twitter.com/femincan">Twitter</a>, and you can read more tutorials like this one <a target="_blank" href="https://femincan.dev">on my blog here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
