<?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[ ES6 - 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[ ES6 - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 17 May 2026 22:28:56 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/es6/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Template Literals in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Template literals are a feature in JavaScript that were introduced with ES6. They give you a more flexible and maintainable way of working with strings in JavaScript. By the end of this article, you will know how to use template literals. You will le... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/template-literals-in-javascript/</link>
                <guid isPermaLink="false">66d45de7d7a4e35e3843494d</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Fri, 05 Jan 2024 18:30:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/JavaScript-template-literal---freecodecamp.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Template literals are a feature in JavaScript that were introduced with ES6. They give you a more flexible and maintainable way of working with strings in JavaScript.</p>
<p>By the end of this article, you will know how to use template literals. You will learn the syntax, the benefits, and some use cases. And you will also learn about an even more powerful feature called tagged template literals.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#what-are-template-literals">What are Template Literals?</a></p>
</li>
<li><p><a class="post-section-overview" href="#template-literals-vs-regular-strings">Template Literals vs Regular Strings</a></p>
</li>
<li><p><a class="post-section-overview" href="#some-practical-use-cases-of-template-literals">Some Use Cases of Template Literals</a></p>
</li>
<li><p><a class="post-section-overview" href="#tagged-template-literals">Tagged Template Literals</a></p>
</li>
<li><p><a class="post-section-overview" href="#practical-example-of-tagged-template-literal">Examples of Tagged Template Literals</a></p>
</li>
<li><p><a class="post-section-overview" href="#conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-are-template-literals">What are Template Literals?</h2>
<p>Template literasl are a feature in JavaScript that let developers work with strings in a convenient way. You denote regular strings in JavaScript using double quotes <code>""</code> or single quotes <code>''</code>.</p>
<p>But with template literals, you denote strings using backticks ````. This lets you embed variables and expressions within your strings.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> website = <span class="hljs-string">'freeCodeCamp'</span>
<span class="hljs-keyword">const</span> message = <span class="hljs-string">`Welcome to <span class="hljs-subst">${website}</span>`</span>

<span class="hljs-built_in">console</span>.log(message)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-03-at-6.57.20-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output of template literal example.</em></p>
<p>The value of the <code>message</code> variable is an example of a template literal. It includes backticks which are used to define the template literal. And it also includes the syntax <code>${}</code> which is used to embed variables within the string.</p>
<h2 id="heading-template-literals-vs-regular-strings">Template Literals vs Regular Strings</h2>
<p>Let's now take a look at how template literals differ from regular strings and also some of the benefits of using template literals.</p>
<h3 id="heading-string-concatenation">String Concatenation</h3>
<p>Before the introduction of template literals, you had to use the plus <code>+</code> symbol when you wanted to concatenate strings.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> userName = <span class="hljs-string">'Marie'</span>
<span class="hljs-keyword">const</span> balance = <span class="hljs-number">10</span>

<span class="hljs-comment">// Using regular string</span>
<span class="hljs-keyword">const</span> str1 = <span class="hljs-string">'Hi '</span> + userName + <span class="hljs-string">','</span> + <span class="hljs-string">' your balance is '</span> + balance + <span class="hljs-string">'.'</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Regular string: "</span>, str1)

<span class="hljs-comment">// Using template literal</span>
<span class="hljs-keyword">const</span> str2 = <span class="hljs-string">`Hi <span class="hljs-subst">${userName}</span>, your balance is <span class="hljs-subst">${balance}</span>.`</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Template literal: "</span>, str2)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-03-at-7.07.37-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The regular string and template literal produce the same output for the example.</em></p>
<p>Note how using regular strings involves adding many plus signs. And also accounting for whitespace at the right places. This can get difficult to deal with when working with lengthy strings.</p>
<p>With the template literal example, there was no need to add any plus signs. You write everything together as a single string. The variables are directly embedded using the <code>${}</code> syntax.</p>
<h3 id="heading-multi-line-strings">Multi-line Strings</h3>
<p>Another way template literals make it easier to work with strings is when dealing with multi line strings. For regular strings, you have to use a combination of the plus <code>+</code> sign and <code>\n</code> to denote a new line. But template literals don't require any of that.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> regularString = 
<span class="hljs-string">'Hello there! \n'</span> +
<span class="hljs-string">'Welcome to our website. \n'</span> +
<span class="hljs-string">'How can we help you today?'</span>

<span class="hljs-keyword">const</span> templateLiteral = 
<span class="hljs-string">`Hello there!
Welcome to our website.
How can we help you today?`</span>

<span class="hljs-built_in">console</span>.log(regularString)
<span class="hljs-built_in">console</span>.log(templateLiteral)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-03-at-7.44.20-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Multi line string examples for regular string and template literal.</em></p>
<p>Both the <code>regularString</code> and <code>templateLiteral</code> variables give the same output. The template string recognises whitespaces and linebreaks automatically.</p>
<h3 id="heading-readability-and-maintainability">Readability and Maintainability</h3>
<p>Template literals also make your code more readable and easier to maintain. As you've seen already, they doesn't require any concatenation with the plus <code>+</code> sign. And you also don't need to worry about escaping quotations marks.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> city = <span class="hljs-string">"Paris"</span>
<span class="hljs-keyword">const</span> str1 = <span class="hljs-string">'She said, "I love '</span> + city + <span class="hljs-string">', it\'s a beautiful place."'</span>
<span class="hljs-keyword">const</span> str2 = <span class="hljs-string">`She said, "I love <span class="hljs-subst">${city}</span>, it's a beautiful place`</span>

<span class="hljs-built_in">console</span>.log(regularString)
<span class="hljs-built_in">console</span>.log(templateLiteral)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-04-at-7.00.42-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Results of regular string and template literal examples</em></p>
<p>Unlike the template literal, the regular string requires the following;</p>
<ul>
<li><p>The use of the plus <code>+</code> for concatenation.</p>
</li>
<li><p>Careful use of single and double quotes.</p>
</li>
<li><p>The need to escape the single quote in string with <code>\</code>.</p>
</li>
</ul>
<h2 id="heading-some-practical-use-cases-of-template-literals">Some Practical Use Cases of Template Literals</h2>
<p>So far, you've learned what template literals are and how they compare with regular strings. Now, let's look at some practical examples.</p>
<h3 id="heading-generating-html-markup">Generating HTML Markup</h3>
<p>You will often see template literals used for generating HTML markup. They allow you to embed JavaScript expressions directly into HTML strings. This makes it easy to create content that's dynamic and data driven.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Marie"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>,
};

<span class="hljs-keyword">const</span> userProfile = <span class="hljs-string">`
&lt;div&gt;
  &lt;h2&gt;Name: <span class="hljs-subst">${user.name}</span>&lt;/h2&gt;
  &lt;p&gt;Age: <span class="hljs-subst">${user.age}</span>&lt;/p&gt;
&lt;/div&gt;
`</span>
</code></pre>
<p>Note how the <code>${}</code> syntax allows you to run JavaScript expressions directly within the string. In this case, it's used to read the values of the <code>user</code> object's properties.</p>
<h3 id="heading-creating-dynamic-sql-queries">Creating Dynamic SQL Queries</h3>
<p>You can also use template literals to create dynamic SQL queries by embedding variables or expressions directly into the query strings. This means you can easily create queries based on runtime values.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> tableName = <span class="hljs-string">"users"</span>;
<span class="hljs-keyword">const</span> columnName = <span class="hljs-string">"name"</span>;
<span class="hljs-keyword">const</span> searchValue = <span class="hljs-string">"John"</span>;

<span class="hljs-keyword">const</span> sqlQuery = 
  <span class="hljs-string">`SELECT * FROM <span class="hljs-subst">${tableName}</span> WHERE <span class="hljs-subst">${columnName}</span> = '<span class="hljs-subst">${searchValue}</span>'`</span>
</code></pre>
<h3 id="heading-localization-and-internalization">Localization and Internalization</h3>
<p>Another practical use of template literals is for handling localization and internationalization in your apps. It's easier to manage translations because with template literals, you can embed variables for localized content or language keys directly into strings.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Marie"</span>,
};

<span class="hljs-keyword">const</span> locale = <span class="hljs-string">"fr"</span>;
<span class="hljs-keyword">const</span> greetings = {
  <span class="hljs-attr">en</span>: <span class="hljs-string">"Hello"</span>,
  <span class="hljs-attr">es</span>: <span class="hljs-string">"Hola"</span>,
  <span class="hljs-attr">fr</span>: <span class="hljs-string">"Bonjour"</span>
};

<span class="hljs-keyword">const</span> localizedGreeting = <span class="hljs-string">`<span class="hljs-subst">${greetings[locale]}</span> <span class="hljs-subst">${user.name}</span>!`</span>;
<span class="hljs-built_in">console</span>.log(localizedGreeting)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-04-at-7.51.34-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of using template literals for localized content.</em></p>
<p>This example creates a <code>localizedGreeting</code> string without relying on any cumbersome concatenation.</p>
<h2 id="heading-tagged-template-literals">Tagged Template Literals</h2>
<p>This is a feature of the JavaScript template literal that you can use to perform advanced string manipulation.</p>
<p>To use this feature, you need a tag function and then a tagged template.</p>
<p>The tagFunction takes in a mix of strings and variables as arguments. It then formats them based on some condition or rules you set.</p>
<p>Then, you call (or run) the tag function by placing it before the opening backtick of the template literal.</p>
<h3 id="heading-syntax-for-tagged-template-literal">Syntax for Tagged Template Literal</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">taggedFunc</span>(<span class="hljs-params">strings, ...values</span>) </span>{
  <span class="hljs-built_in">console</span>.log(strings)
  <span class="hljs-built_in">console</span>.log(values)
}

<span class="hljs-keyword">const</span> name = <span class="hljs-string">'Sarah'</span>
<span class="hljs-keyword">const</span> city = <span class="hljs-string">'Rome'</span>

taggedFunc<span class="hljs-string">`Hello <span class="hljs-subst">${name}</span>. Welcome to <span class="hljs-subst">${city}</span>.`</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-04-at-10.03.12-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results for the string and value arguments of a tagged template literal</em></p>
<p>There are three things to take note of here.</p>
<p>First, the first parameter (<code>strings</code> in this example) is always an array of all the blocks of strings in the template literal. In this case, it is the array below.</p>
<pre><code class="lang-javascript">[<span class="hljs-string">'Hello '</span>, <span class="hljs-string">'. Welcome to '</span>, <span class="hljs-string">'.'</span>]
</code></pre>
<p>Next, the rest of the parameters will be all the variables and evaluated expressions within the template literals. The <a target="_blank" href="https://www.freecodecamp.org/news/javascript-rest-vs-spread-operators/">JavaScript rest parameter</a> syntax <code>...values</code> makes it simple to get all of them.</p>
<pre><code class="lang-javascript">[<span class="hljs-string">'Sarah'</span>, <span class="hljs-string">'Rome'</span>]
</code></pre>
<p>Finally, take note of how the <code>taggedFunc</code> is used. Unlike a regular function, you won't call it with a parenthesis. But by attaching it before the first backtick of the template literal.</p>
<pre><code class="lang-javascript">taggedFunc<span class="hljs-string">`Hello <span class="hljs-subst">${name}</span>. Welcome to <span class="hljs-subst">${city}</span>.`</span> ✅

taggedFunc(Hello ${name}. Welcome to ${city}.) ❌
</code></pre>
<h2 id="heading-practical-example-of-tagged-template-literal">Practical Example of Tagged Template Literal</h2>
<p>Now let's see some practical examples of using a tagged template literal to handle string manipulation.</p>
<h3 id="heading-example-1">Example 1</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">receiptTag</span>(<span class="hljs-params">strings, ...values</span>) </span>{  

  <span class="hljs-keyword">let</span> finalString = <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; values.length; i++) {
    finalString += strings[i] + values[i]
  }

  <span class="hljs-comment">// Add the last string literal</span>
  finalString += strings[strings.length - <span class="hljs-number">1</span>] 

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

<span class="hljs-keyword">const</span> item = <span class="hljs-string">'apple'</span>
<span class="hljs-keyword">const</span> price = <span class="hljs-number">2.5</span>
<span class="hljs-keyword">const</span> quantity = <span class="hljs-number">3</span>

<span class="hljs-keyword">const</span> message = receiptTag<span class="hljs-string">`
  You have <span class="hljs-subst">${quantity}</span> <span class="hljs-subst">${item}</span>s.
  Unit cost: $<span class="hljs-subst">${price}</span>. 
  Total cost: $<span class="hljs-subst">${quantity * price}</span>.
`</span>

<span class="hljs-built_in">console</span>.log(message)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-04-at-10.37.18-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of a string formatted with a tagged template literal.</em></p>
<p>In this example, the <code>recieptTag</code> function receives a template literal with four expressions:</p>
<ul>
<li><p><code>${quantity}</code></p>
</li>
<li><p><code>${item}</code></p>
</li>
<li><p><code>${price}</code></p>
</li>
<li><p><code>${quantity * price}</code></p>
</li>
</ul>
<p>The <code>values</code> array will contain the evaluated values of these expressions.</p>
<pre><code class="lang-javascript">[<span class="hljs-number">3</span>, <span class="hljs-string">'apple'</span>, <span class="hljs-number">2.5</span>, <span class="hljs-number">7.5</span>]
</code></pre>
<p>And you can process them accordingly in the tagged function.</p>
<p>The result, logged to the console is a <code>message</code> that includes information about the quantity, item, unit cost and total cost.</p>
<h3 id="heading-example-2">Example 2</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetUser</span>(<span class="hljs-params">strings, name</span>) </span>{
  <span class="hljs-keyword">const</span> now = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()
  <span class="hljs-keyword">const</span> currentHour = now.getHours()

  <span class="hljs-keyword">const</span> timeOfDay = currentHour &lt; <span class="hljs-number">12</span> ? <span class="hljs-string">'morning'</span> : currentHour &lt; <span class="hljs-number">17</span> ? <span class="hljs-string">'afternoon'</span> : <span class="hljs-string">'evening'</span>

  <span class="hljs-keyword">return</span> <span class="hljs-string">`Good <span class="hljs-subst">${timeOfDay}</span> <span class="hljs-subst">${name}</span><span class="hljs-subst">${strings[<span class="hljs-number">1</span>]}</span>`</span>
}

<span class="hljs-keyword">const</span> userName = <span class="hljs-string">'Ama'</span>

<span class="hljs-built_in">console</span>.log(greetUser<span class="hljs-string">`Hello <span class="hljs-subst">${userName}</span>, nice to meet you!`</span>)
</code></pre>
<p>This example uses tagged template literal to determine how to greet the user based on what time of day it is.</p>
<p>The function first gets the current hour using the date object. Then uses a tenary operator to determin time of day. And returns a string with a <code>timeOfDay</code> variable indicating what time of day it is.</p>
<p>Also, pay attention to the first word of the log statement and compare it to the first word of the string passed to the tag to see how the function has changed the string.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Template literals provide a convenient way to work with strings in JavaScript. In this article, you've learned about the syntax, and how to use them in your projects.</p>
<p>You also learned about an advanced feature of template literals: tagged template literals. These are functions that take in an array of string blocks and expressions. They return a string based on the logic you write for the function.</p>
<p>Thanks for reading. And happy coding! For more in-depth tutorials, feel free to <a target="_blank" href="https://www.youtube.com/@DevAfterHours">subscribe to my YouTube channel</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Bypass ES Modules Errors in Next.js with Dynamic Imports ]]>
                </title>
                <description>
                    <![CDATA[ By Caleb Olojo When you are building an application that can be accessed on the web, there are a lot of dependencies or packages that you will need for your application to function well. You'll need most of these packages when you're building JAMStac... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-bypass-es-modules-error-in-next-js/</link>
                <guid isPermaLink="false">66d45ddd8812486a37369c7b</guid>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 19 Apr 2022 19:58:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/tim-gouw-1K9T5YiZ2WU-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Caleb Olojo</p>
<p>When you are building an application that can be accessed on the web, there are a lot of dependencies or packages that you will need for your application to function well.</p>
<p>You'll need most of these packages when you're building JAMStack applications with frameworks or libraries like React, Vuejs, Next.js, or Angular.</p>
<p>In this article, I'll walk you through an error you may get when you are building JavaScript apps with Next.js, and how to bypass it.</p>
<h2 id="heading-what-the-heck-are-esmodules">What the Heck are ESModules?</h2>
<p>ESModules are the ECMAScript standards for working with JavaScript modules in the browser.</p>
<p>"What does that have to do with these annoying and frustrating errors that I have been seeing for the past few days?" you might ask me.</p>
<p>Well... Node.js has been using the <strong>CommonJS</strong> standards for a very long time to properly structure JavaScript code or modules in this scenario, and the majority of the code we write resides/works in the browser.</p>
<p>There were no standards to properly guide how JavaScript modules were used, or interpreted, at least in web browsers. This challenge brought about the ESModules standards which guide how JavaScript modules work in the browser.</p>
<p>This standard was approved when ES6 (ECMAScript 6) was launched in 2015, and brought about the implementation of the standards in various web browsers like Chrome, Safari, Firefox, and Microsoft's Edge.</p>
<p>Most of the packages we use in building frontend UIs are written in JavaScript. They have modules that are exporting a particular function (it could be a JavaScript component), an object, a string, a bunch of arrays, and so on.</p>
<p>These functions, arrays, or strings can be exposed as libraries to other JavaScript files. Say, for example, we have a function that prints the name of anyone in the console. The syntax will be like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// name.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> (name) =&gt; <span class="hljs-built_in">console</span>.log(name)
</code></pre>
<p>The snippet above describes a default export, without a specific name. This means that if we want to use the function in this module, we can call it any name, since a name wasn't explicitly assigned to it upon declaration</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> printName <span class="hljs-keyword">from</span> <span class="hljs-string">"./name.js"</span>

printName(<span class="hljs-string">"Dodo"</span>)
</code></pre>
<h2 id="heading-okay-why-do-i-still-get-the-error-though">Okay, why do I still get the error though?</h2>
<p>Yes. Now on to that error. When we begin to interface with a lot of dependencies or packages in our applications, some things might start going wrong if we don't give proper care to our codebases.</p>
<p>We start to deal with versioning of these packages, breaking changes, and releases sometimes, which we can not keep track of. Then, we might begin to scurry down the rabbit hole of downgrading or upgrading a particular npm package before anything even works at all.</p>
<p>Most of these errors may arise from the maintainers of these packages. Take, for example, the ESModules standard – which is relatively new – that we are discussing in this article. It may take some time for it to be adopted by some frameworks or front-end JavaScript libraries out there, for example, Next.js.</p>
<p>The error in the image below shows that we can't use the CommonJS approach to import a module.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/serialize-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This new standard and the fact that it's a bit unfamiliar to these tools we use is the reason for this error. <a target="_blank" href="https://www.smashingmagazine.com/2021/11/maintain-large-nextjs-application/">Nirmalya Ghosh wrote this piece on how to maintain large Next.js apps</a>, you should take a look at it.</p>
<h2 id="heading-how-to-use-nextjs-dynamic-imports">How to use Next.js dynamic imports</h2>
<p>Now that we've gone through the rudiments of what ESModules are, let's see how we can fix the error that is quite similar to the one we saw in the image above. We'll see how we can fix it with dynamic imports in Next.js.</p>
<p>I'll be assuming you already have a Next.js app running, so I'll just share the corresponding ESModule error I got from my terminal in the code block below:</p>
<pre><code class="lang-bash">Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /path/to/package

require() of ES modules is not supported. 

ES module file as it is a .js file whose nearest parent package.json contains <span class="hljs-string">"type"</span>: <span class="hljs-string">"module"</span> <span class="hljs-built_in">which</span> defines all .js files <span class="hljs-keyword">in</span> that package scope as ES modules.

Instead rename index.js to end <span class="hljs-keyword">in</span> .cjs, change the requiring code to use import(), or remove <span class="hljs-string">"type"</span>: <span class="hljs-string">"module"</span> from /path/to/package
</code></pre>
<p>Take a look at the error above so that you're quite familiar with it. Once you've done that, let's proceed.</p>
<h3 id="heading-what-are-dynamic-imports">What are dynamic imports?</h3>
<p>Dynamic imports is a feature of Next.js that allows you to work with JavaScript modules conveniently in the browser.</p>
<p>It provides a means of pre-rendering these modules with SSR (Server-side Rendering) so that users do not need to send requests continuously to the server when they need — say, for example — a page that uses a JavaScript module. With dynamic imports, the modules are already pre-rendered in the browser.</p>
<p>Recently, I was working on a project that had to do with markdown content. I needed to use rehype plugins, but I kept on getting the error in the previous code block.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> rehypeSlug = dynamic(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'rehype-slug'</span>), { <span class="hljs-attr">ssr</span>: <span class="hljs-literal">false</span> })
<span class="hljs-keyword">const</span> rehypeCodeTitles = dynamic(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'rehype-code-titles'</span>), {
  <span class="hljs-attr">ssr</span>: <span class="hljs-literal">false</span>,
})
<span class="hljs-keyword">const</span> rehypeAutolinkHeadings = dynamic(
  <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'rehype-autolink-headings'</span>),
  { <span class="hljs-attr">ssr</span>: <span class="hljs-literal">false</span> }
)
<span class="hljs-keyword">const</span> rehypePrism = dynamic(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'rehype-prism-plus'</span>), { <span class="hljs-attr">ssr</span>: <span class="hljs-literal">false</span> })
</code></pre>
<p>The snippet above shows how you can import a module with dynamic imports and pass the <code>ssr</code> object as an argument to it.</p>
<p>With this approach of using dynamic imports, the ESModule errors that kept on showing up were removed.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>So I hope you'll be able to make use of this feature, and I hope it liberates you from that error. </p>
<p>There's a lot you have to think about when you're building JavaScript applications, so this can be one less thing. Thank you for reading this article, and I hope you enjoyed it.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use ES6 Features in React ]]>
                </title>
                <description>
                    <![CDATA[ Many JavaScript frameworks use ES6 features. So to help you learn these handy features, I'll introduce you to them and then show you how to apply them in React.js.  Here are the ES6 features we'll cover in this guide: Modules Destructuring Spread Op... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-es6-javascript-features-in-react/</link>
                <guid isPermaLink="false">66b0a2eb7cd8dca6718a2246</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Thu, 28 Oct 2021 15:23:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/g30.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Many JavaScript frameworks use ES6 features. So to help you learn these handy features, I'll introduce you to them and then show you how to apply them in React.js. </p>
<p>Here are the ES6 features we'll cover in this guide:</p>
<ul>
<li>Modules</li>
<li>Destructuring</li>
<li>Spread Operator</li>
<li>Arrow functions</li>
<li>Template Literals</li>
</ul>
<p>All the examples we'll see here are quite basic and should be easy for beginners to grasp.</p>
<h2 id="heading-how-to-use-es6-modules">How to Use ES6 Modules</h2>
<p>Modules help you split various functionalities of your app into separate files/scripts. You can have different scripts for form validation, logging a user in, and so on. </p>
<p>Here, we will have two scripts: one for adding numbers and the other for subtracting numbers. We will take it step by step.</p>
<p>This is the structure of our folder:</p>
<blockquote>
<p>index.html<br>script.js<br>myModules/<br> add.js<br> sub.js</p>
</blockquote>
<p>First we'll see how to use modules in vanilla JavaScript. Then we'll see how to apply them in React.</p>
<h3 id="heading-step-1-create-the-html-file-and-link-your-script">Step 1 – Create the HTML file and link your script</h3>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES6 Modules<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>You will notice that the script tag has a <code>type</code> which has the value of <code>module</code>. That should be the first thing you do if you are going to use the Module feature. </p>
<p>You may come across resources that use a different method like adding a <code>.mjs</code> extension to their files, but to be on the safe side I'd recommend this method. The <code>script.js</code> will act as the "parent script" which we will be importing our modules into. </p>
<h3 id="heading-step-2-create-and-export-functions-into-separate-files">Step 2 – Create and export functions into separate files</h3>
<p>Here's the function for addition in <code>add.js</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>)</span>{
    <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>Here's the function for subtraction in <code>sub.js</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sub</span>(<span class="hljs-params">a, b</span>)</span>{
    <span class="hljs-keyword">return</span> a - b;
}
</code></pre>
<p>Did you notice the <code>export</code> statement? To be able to use these functions in other scripts, you have to export them by adding the <code>export</code> statement. </p>
<p>Here, we used inline export by adding the statement before the function – but you can opt to export this function at the bottom of the document like this: <code>export default add;</code>.</p>
<h3 id="heading-step-3-import-the-functions-into-scriptjs">Step 3 – Import the functions into <code>script.js</code></h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { add } <span class="hljs-keyword">from</span> <span class="hljs-string">"./myModules/add.js"</span>;
<span class="hljs-keyword">import</span> { sub } <span class="hljs-keyword">from</span> <span class="hljs-string">"./myModules/sub.js"</span>

<span class="hljs-built_in">console</span>.log(add(<span class="hljs-number">6</span>, <span class="hljs-number">4</span>)); <span class="hljs-comment">// 10</span>

<span class="hljs-built_in">console</span>.log(sub(<span class="hljs-number">6</span>, <span class="hljs-number">4</span>));  <span class="hljs-comment">// 2</span>
</code></pre>
<p>To import the <code>add</code> function, we first typed the <code>import</code> statement followed by the name of the function nested in curly brackets and then the path to the file which the function exists in. </p>
<p>You can see how we used <code>add(6, 4);</code> without reinventing the wheel by creating the function from scratch. Now you can import this function into any script you want.</p>
<h3 id="heading-step-4-how-to-apply-modules-in-reactjs">Step 4 – How to apply modules in React.js</h3>
<p>Now that you have seen how we can use modules in vanilla JavaScript, let's have look at how you can use them in a React app. </p>
<p>When you create a React application, the <code>App.js</code> component usually acts as the main component. We are going to create another component called <code>User.js</code> with some content about a user.</p>
<p>Here's the <code>App.js</code> component:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>

    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>This component has just a <code>div</code> without any content.</p>
<p>And here's the <code>User.js</code> component: </p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My name is Ihechikara.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>I am a web developer.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>I love writing.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> User
</code></pre>
<p>If you can recall, you can export your functions at the bottom of the script as we just did. Next, we will import this function into the <code>App.js</code> component:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> User <span class="hljs-keyword">from</span> <span class="hljs-string">"./User"</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">User</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>Just two additions to the script: <code>import User from "./User"</code> which point to the location of the component, and <code>&lt;User/&gt;</code> being the component itself. </p>
<p>Now you can reuse the logic in the <code>User.js</code> component across your app and you can make it more dynamic using props instead of hard coding the user's information – but that is beyond the scope of this tutorial.</p>
<h2 id="heading-how-to-use-es6-destructuring">How to Use ES6 Destructuring</h2>
<p>To destructure means to dismantle the structure of something. In JavaScript, this structure could be an array, an object, or even a string where the properties that make up the structure would be used to create a new identical structure (the properties can be altered). </p>
<p>If what I have said still seems abstract to you, don't worry because you will understand better from the examples.</p>
<p>Prior to ES6, this is how you would extract some data in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> scores = [<span class="hljs-number">500</span>, <span class="hljs-number">400</span>, <span class="hljs-number">300</span>];

<span class="hljs-keyword">var</span> x = scores[<span class="hljs-number">0</span>],
    y = scores[<span class="hljs-number">1</span>],
    z = scores[<span class="hljs-number">2</span>];

    <span class="hljs-built_in">console</span>.log(x,y,z); <span class="hljs-comment">// 500 400 300</span>
</code></pre>
<p>But in ES6, using destructuring, we can do this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> scores = [<span class="hljs-number">500</span>, <span class="hljs-number">400</span>, <span class="hljs-number">300</span>];

<span class="hljs-keyword">let</span> [x, y, z] = scores;

<span class="hljs-built_in">console</span>.log(x,y,z); <span class="hljs-comment">//500 400 300</span>
</code></pre>
<p>The x, y and z variables will inherit the values in the scores array in the order which they appear, so <code>x = 500</code>, <code>y = 400</code> and <code>z = 300</code>. In a situation where all the values in the array have been inherited, any other value left without a parent value will return as undefined. That is:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> scores = [<span class="hljs-number">500</span>, <span class="hljs-number">400</span>, <span class="hljs-number">300</span>];

<span class="hljs-keyword">let</span> [x, y, z, w] = scores;

<span class="hljs-built_in">console</span>.log(x,y,z,w); <span class="hljs-comment">//500 400 300 undefined</span>
</code></pre>
<p>Here is an example using objects:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> scores = {
    <span class="hljs-attr">pass</span>: <span class="hljs-number">70</span>,
    <span class="hljs-attr">avg</span>: <span class="hljs-number">50</span>,
    <span class="hljs-attr">fail</span>: <span class="hljs-number">30</span>
};

<span class="hljs-keyword">let</span> { pass, avg, fail} = scores;

<span class="hljs-built_in">console</span>.log(pass, avg, fail); <span class="hljs-comment">// 70 50 30</span>
</code></pre>
<p>The process is the same as destructuring arrays. </p>
<p>Here is another example, but with strings:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> [user, interface] = <span class="hljs-string">'UI'</span>;

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

<span class="hljs-built_in">console</span>.log(interface); <span class="hljs-comment">// I</span>
</code></pre>
<p>The string was split into individuals letters and then assigned to the variables in the array.</p>
<h3 id="heading-how-to-use-destructuring-in-reactjs">How to use destructuring in React.js</h3>
<p>There are various scenarios where you might want to use destructuring in React. But a very common one would be with the <code>useState</code> hook.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { 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">TestDestructuring</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> [grade, setGrade] = useState(<span class="hljs-string">'A'</span>);

    <span class="hljs-keyword">return</span>(
        <span class="xml"><span class="hljs-tag">&lt;&gt;</span>

        <span class="hljs-tag">&lt;/&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> TestDestructuring
</code></pre>
<p>Above, we created a constant variable <code>grade</code> along with a function <code>setGrade</code> whose purpose is to update the value of the variable. And we set the value of  <code>grade</code> to 'A' using destructuring. </p>
<h2 id="heading-how-to-use-the-es6-spread-operator">How to Use the ES6 Spread Operator</h2>
<p>The spread operator <code>...</code> lets you copy all or some parts of an array, object, or string into another array, object, or string. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> collectionOne = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>];
<span class="hljs-keyword">const</span> collectionTwo = [<span class="hljs-number">40</span>, <span class="hljs-number">50</span>, <span class="hljs-number">60</span>];

<span class="hljs-keyword">const</span> allCollections = [...collectionOne, ...collectionTwo];

<span class="hljs-built_in">console</span>.log(allCollections); <span class="hljs-comment">//10, 20, 30, 40, 50, 60</span>
</code></pre>
<p>There is really not much to this. Using the <code>...</code> symbol, all the values of the first two collections were assigned to the third collection. </p>
<p>Now that we have all the collections in one array, we will use the spread operator to copy the array and output the highest number. That is:</p>
<pre><code><span class="hljs-keyword">const</span> allCollections = [<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-number">60</span>];

<span class="hljs-keyword">const</span> maxNumber = <span class="hljs-built_in">Math</span>.max(...allCollections);
<span class="hljs-built_in">console</span>.log(maxNumber) <span class="hljs-comment">//60</span>
</code></pre><h3 id="heading-how-to-combine-the-spread-operator-with-destructuring">How to combine the spread operator with destructuring</h3>
<p>In the last section, we saw the application of destructuring in JavaScript. Now, let's see how we can combine destructuring and the spread operator:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> scores = [<span class="hljs-number">500</span>, <span class="hljs-number">400</span>, <span class="hljs-number">300</span>];

<span class="hljs-keyword">let</span> [x, ...y] = scores;

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

<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// [400, 300]</span>
</code></pre>
<p>Here, the <code>x</code> variable inherited the first number in the array then the <code>y</code> variable spread across the array and copied everything that was left.</p>
<h2 id="heading-how-to-use-es6-arrow-functions">How to Use ES6 Arrow Functions</h2>
<p>Basically, arrow functions allows us write our functions using shorter syntax. Before ES6, this is how you would write a function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> greetings = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>)
}

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

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetings2</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"HI!"</span>)
}
</code></pre>
<p>With ES6, a different syntax was introduced:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> greetings = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>)
}

<span class="hljs-keyword">var</span> greetings = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"HI!"</span>)
}
</code></pre>
<p>The <code>function</code> keyword was removed while the fat arrow operator <code>=&gt;</code> was introduced. </p>
<p>Note that arrow functions are anonymous.</p>
<h3 id="heading-how-to-use-arrow-functions-with-parameters">How to use arrow functions with parameters</h3>
<p>Parameters in arrow functions are passed into the parenthesis that come before the fat arrow operator. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> add = <span class="hljs-function">(<span class="hljs-params">a,b</span>)=&gt;</span>{
  <span class="hljs-keyword">return</span> a + b;
}
<span class="hljs-built_in">console</span>.log(add(<span class="hljs-number">2</span>,<span class="hljs-number">2</span>)) <span class="hljs-comment">//4</span>
</code></pre>
<h2 id="heading-how-to-use-es6-template-literals">How to Use ES6 Template Literals</h2>
<p>Template literals allow you use back-ticks (``) instead of quotes ("") to define a string. This has various advantages.</p>
<p>Before ES6:</p>
<pre><code><span class="hljs-keyword">var</span> name = <span class="hljs-string">"My name is Ihechikara"</span> 

<span class="hljs-built_in">console</span>.log(fullname);
</code></pre><p>With ES6:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> name = <span class="hljs-string">`My name is Ihechikara`</span> 

<span class="hljs-built_in">console</span>.log(fullname);
</code></pre>
<h3 id="heading-interpolation-in-template-literals">Interpolation in template literals</h3>
<p>String interpolation lets you include variables and statements in your strings without breaking it up with the <code>+</code> operator. That is:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> me = <span class="hljs-string">'Ihechikara'</span>;

<span class="hljs-keyword">var</span> fullname = <span class="hljs-string">`My name is Abba <span class="hljs-subst">${me}</span>`</span>;

<span class="hljs-built_in">console</span>.log(fullname);
</code></pre>
<p>To interpolate a variable into your string, you use <code>${}</code> with the name of the variable passed into the curly brackets. Always remember that your string must be nested inside back-ticks and not quotation marks. </p>
<p>The same applies when you are creating your DOM elements dynamically with JavaScript. You would do something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name = <span class="hljs-string">'Ihechikara'</span>;
<span class="hljs-keyword">let</span> myHtmlTemplate = <span class="hljs-string">`&lt;h1&gt; This is a paragraph created by <span class="hljs-subst">${name}</span>&lt;/h1&gt;`</span>;
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article covered some of the most important ES6 features like modules, destructuring, spread operator, arrow functions and template literals. </p>
<p>You will see these features being used frequently while learning or understanding JavaScript frameworks, so it should help you grasp their application in whatever framework they appear. </p>
<p>If you have any questions about these features, you can find me on Twitter <a target="_blank" href="https://twitter.com/Ihechikara2">@ihechikara2</a>. Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Modern JavaScript – Imports, Exports, Let, Const, and Promises in ES6+ ]]>
                </title>
                <description>
                    <![CDATA[ Over the past few years, there have been many updates to the JavaScript language. And these updates are very useful if you want to improve your coding. ​Keeping abreast of the newest developments in the language is really important. It can help you g... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-modern-javascript/</link>
                <guid isPermaLink="false">66bc5527d94fa6cb67b84502</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Yogesh Chavan ]]>
                </dc:creator>
                <pubDate>Mon, 07 Dec 2020 22:47:10 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5fcb4bbce6787e098393a6fd.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Over the past few years, there have been many updates to the JavaScript language. And these updates are very useful if you want to improve your coding.</p>
<p>​Keeping abreast of the newest developments in the language is really important. It can help you get a higher paying job, keep up to date with the latest trends, improve your code quality, and excel in your current job.</p>
<p>And you definitely need to know the latest features if you're trying to learn a JavaScript library like React or framework like Angular or Vue.</p>
<p>Recently, there have been many useful additions to JavaScript like the <strong>Nullish coalescing operator</strong>, <strong>optional chaining</strong>, <strong>Promises</strong>, <strong>async/await</strong>, <strong>ES6 destructuring</strong>, and more.</p>
<p>So today, we will look at some of these concepts which every JavaScript developer should be aware of.</p>
<p>Let's get started and dive into the things you need to know about JS.</p>
<h2 id="heading-let-and-const-in-javascript">Let and const in JavaScript</h2>
<p>Before ES6, JavaScript used the <code>var</code> keyword which only used function and global scope. There was no block-level scope.</p>
<p>With the addition of <code>let</code> and <code>const</code> JavaScript added block scoping.</p>
<h3 id="heading-how-to-use-let-in-javascript">How to use let in JavaScript</h3>
<p>When we declare a variable using the <code>let</code> keyword, we can <strong>assign</strong> a new value to that variable later but we cannot <strong>re-declare</strong> it with the same name.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 Code</span>
<span class="hljs-keyword">var</span> value = <span class="hljs-number">10</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// 10</span>

<span class="hljs-keyword">var</span> value = <span class="hljs-string">"hello"</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// hello</span>

<span class="hljs-keyword">var</span> value = <span class="hljs-number">30</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// 30</span>
</code></pre>
<p>As you can see above, we have re-declared the variable <code>value</code> using the <code>var</code> keyword multiple times.</p>
<p>Before ES6, we were able to re-declare a variable that had already been declared before if it wasn't used meaningfully and was instead causing confusion.</p>
<p>But what if we already had a variable declared with the same name somewhere else and we're re-declaring it without realizing it? Then we might override the variable value, causing some difficult to debug issues.</p>
<p>So when you use the <code>let</code> keyword, you will get an error when you try to re-declare the variable with the same name – which is a good thing.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES6 Code</span>
<span class="hljs-keyword">let</span> value = <span class="hljs-number">10</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// 10</span>

<span class="hljs-keyword">let</span> value = <span class="hljs-string">"hello"</span>; <span class="hljs-comment">// Uncaught SyntaxError: Identifier 'value' has already been declared</span>
</code></pre>
<p>But, the following code is valid:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES6 Code</span>
<span class="hljs-keyword">let</span> value = <span class="hljs-number">10</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// 10</span>

value = <span class="hljs-string">"hello"</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// hello</span>
</code></pre>
<p>We don't get an error in the above code because we're <strong>re-assigning</strong> a new value to the  <code>value</code> variable. But we're <strong>not re-declaring</strong> <code>value</code> again.</p>
<p>Now, take a look at the below code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 Code</span>
<span class="hljs-keyword">var</span> isValid = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">if</span>(isValid) {
  <span class="hljs-keyword">var</span> number = <span class="hljs-number">10</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside:'</span>, number); <span class="hljs-comment">// inside: 10</span>
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, number); <span class="hljs-comment">// outside: 10</span>
</code></pre>
<p>As you can see in this code, when we declare a variable with the <code>var</code> keyword, it's available outside the <code>if</code> block also.</p>
<p>Now take a look at the below code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES6 Code</span>
<span class="hljs-keyword">let</span> isValid = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">if</span>(isValid) {
  <span class="hljs-keyword">let</span> number = <span class="hljs-number">10</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside:'</span>, number); <span class="hljs-comment">// inside: 10</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, number); <span class="hljs-comment">// Uncaught ReferenceError: number is not defined</span>
</code></pre>
<p>As you can see, the <code>number</code> variable when declared using the <code>let</code> keyword is only accessible inside the <code>if</code> block. Outside the block it's not available, so we got a reference error when we tried to access it outside the <code>if</code> block.</p>
<p>But if there is a <code>number</code> variable outside the <code>if</code> block, then it will work as shown below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES6 Code</span>
<span class="hljs-keyword">let</span> isValid = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">let</span> number = <span class="hljs-number">20</span>;

<span class="hljs-keyword">if</span>(isValid) {
  <span class="hljs-keyword">let</span> number = <span class="hljs-number">10</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside:'</span>, number); <span class="hljs-comment">// inside: 10</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, number); <span class="hljs-comment">// outside: 20</span>
</code></pre>
<p>Here, we have two <code>number</code> variables in a separate scope. So outside the <code>if</code> block, the value of <code>number</code> will be 20.</p>
<p>Take a look at the below code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 Code</span>
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++){
 <span class="hljs-built_in">console</span>.log(i);
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, i); <span class="hljs-comment">// 10</span>
</code></pre>
<p>When using the <code>var</code> keyword, <code>i</code> is available even outside the <code>for</code> loop.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES6 Code</span>
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++){
 <span class="hljs-built_in">console</span>.log(i);
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, i); <span class="hljs-comment">// Uncaught ReferenceError: i is not defined</span>
</code></pre>
<p>But when using the <code>let</code> keyword, it's not available outside the loop.</p>
<p>So as you can see from the above code samples, using <code>let</code> makes the variable available only inside that block and it's not accessible outside the block.</p>
<p>We can also create a block by a pair of curly brackets like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> i = <span class="hljs-number">10</span>;
{
 <span class="hljs-keyword">let</span> i = <span class="hljs-number">20</span>;
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside:'</span>, i); <span class="hljs-comment">// inside: 20</span>
 i = <span class="hljs-number">30</span>;
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'i again:'</span>, i); <span class="hljs-comment">// i again: 30</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, i); <span class="hljs-comment">// outside: 10</span>
</code></pre>
<p>If you remember, I said we cannot re-declare a <code>let</code> based variable in the same block but we can re-declare it in another block. As you can see in the above code, we have re-declared <code>i</code> and assigned a new value of <code>20</code> inside the block. Once declared, that variable value will be available only in that block.</p>
<p>Outside the block, when we printed that variable, we got <code>10</code> instead of the previously assigned value of <code>30</code> because outside the block, the inside <code>i</code> variable does not exist.</p>
<p>If we don't have the variable <code>i</code> declared outside, then we'll get an error as you can see in the below code:</p>
<pre><code class="lang-js">{
 <span class="hljs-keyword">let</span> i = <span class="hljs-number">20</span>;
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside:'</span>, i); <span class="hljs-comment">// inside: 20</span>
 i = <span class="hljs-number">30</span>;
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'i again:'</span>, i); <span class="hljs-comment">// i again: 30</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, i); <span class="hljs-comment">// Uncaught ReferenceError: i is not defined</span>
</code></pre>
<h3 id="heading-how-to-use-const-in-javascript">How to use const in JavaScript</h3>
<p>The <code>const</code> keyword works exactly the same as the <code>let</code> keyword in its block scoping functionality. So let's look at how they differ from each other.</p>
<p>When we declare a variable as <code>const</code>, it's considered a constant variable whose value will never change.</p>
<p>In the case of <code>let</code>, we're able to assign a new value to that variable later like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> number = <span class="hljs-number">10</span>;
number = <span class="hljs-number">20</span>;

<span class="hljs-built_in">console</span>.log(number); <span class="hljs-comment">// 20</span>
</code></pre>
<p>But we can't do that in case of <code>const</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> number = <span class="hljs-number">10</span>;
number = <span class="hljs-number">20</span>; <span class="hljs-comment">// Uncaught TypeError: Assignment to constant variable.</span>
</code></pre>
<p>We can't even <strong>re-declare</strong> a <code>const</code> variable.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> number = <span class="hljs-number">20</span>;
<span class="hljs-built_in">console</span>.log(number); <span class="hljs-comment">// 20</span>

<span class="hljs-keyword">const</span> number = <span class="hljs-number">10</span>; <span class="hljs-comment">// Uncaught SyntaxError: Identifier 'number' has already been declared</span>
</code></pre>
<p>Now, take a look at the below code:</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>];

arr.push(<span class="hljs-number">5</span>);

<span class="hljs-built_in">console</span>.log(arr); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
</code></pre>
<p>We said that the <code>const</code> variable is constant whose value will never change – but we have changed the constant array above. So how does that make sense?</p>
<blockquote>
<p>Note: Arrays are reference types and not primitive types in JavaScript</p>
</blockquote>
<p>So what actually gets stored in <code>arr</code> is not the actual array but only the reference (address) of the memory location where the actual array is stored.</p>
<p>So by doing <code>arr.push(5);</code> we're not actually changing the reference where the <code>arr</code> points to, but we're changing the values stored at that reference.</p>
<p>The same is the case with objects:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = {
 <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span>,
 <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>
};

obj.age = <span class="hljs-number">40</span>;

<span class="hljs-built_in">console</span>.log(obj); <span class="hljs-comment">// { name: 'David', age: 40 }</span>
</code></pre>
<p>Here, also we're not changing the reference of where the <code>obj</code> points to but we're changing the values stored at that reference.</p>
<p>So the above code will work, but the below code will not work.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
<span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Mike'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">40</span> };
obj = obj1; <span class="hljs-comment">// Uncaught TypeError: Assignment to constant variable.</span>
</code></pre>
<p>The above code does not work because we're trying to change the reference that the  <code>const</code> variable points to.</p>
<p>So the key point to remember when using const is that, when we declare a variable as a constant using const we cannot re-define it. We also cannot re-assign that variable, but we can change the values stored at that location if the variable is of reference type.</p>
<p>So the below code is invalid because we're re-assigning a new value 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>];
arr = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>]; <span class="hljs-comment">// Uncaught TypeError: Assignment to constant variable.</span>
</code></pre>
<p>But note that we can change the values inside the array, as we saw previously.</p>
<p>The following code of re-defining a <code>const</code> variable is also invalid.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> name = <span class="hljs-string">"David"</span>;
<span class="hljs-keyword">const</span> name = <span class="hljs-string">"Raj"</span>; <span class="hljs-comment">// Uncaught SyntaxError: Identifier 'name' has already been declared</span>
</code></pre>
<h3 id="heading-let-and-const-wrap-up">let and const wrap up</h3>
<ul>
<li>The keywords <code>let</code> and <code>const</code> add block scoping in JavaScript.</li>
<li>When we declare a variable as <code>let</code>, we cannot <code>re-define</code> or <code>re-declare</code> another let variable with the same name in the same scope (function or block scope) but we can <code>re-assign</code> a value to it.</li>
<li>When we declare a variable as <code>const</code>, we cannot <code>re-define</code> or <code>re-declare</code> another <code>const</code> variable with the same name in the same scope (function or block scope). But we can change the values stored in that variable if the variable is of a reference type like an array or object.</li>
</ul>
<p>Alright, let's move on to the next big topic: promises.</p>
<h2 id="heading-promises-in-javascript">Promises in JavaScript</h2>
<p>Promises are one of the most important yet confusing and difficult to understand part of JavaScript. And most new devs, as well as experienced ones, struggle to understand them.</p>
<p>Promises were added in ES6 as a native implementation.</p>
<p>So what is a promise? A promise represents an asynchronous operation to be completed in the future.</p>
<p>Previously, Before ES6, there was no way to wait for something to perform some operation.</p>
<p>For example, when we wanted to make an API call, there was no way to wait until the results came back before ES6.</p>
<p>For that, we used to use external libraries like Jquery or Ajax which had their own implementation of promises. But there was no browser implemented promise thing.</p>
<p>But now using Promises in ES6, we can make an API call ourselves and wait until it's done to perform some operation.</p>
<h3 id="heading-how-to-create-a-promise">How to create a Promise</h3>
<p>To create a promise we need to use the <code>Promise</code> constructor function like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{

});
</code></pre>
<p>The <code>Promise</code> constructor takes a function as an argument and that function internally receives <code>resolve</code> and <code>reject</code> as parameters.</p>
<p>The <code>resolve</code> and <code>reject</code> parameters are actually functions that we can call depending on the outcome of the asynchronous operation.</p>
<p>A <code>Promise</code> goes through three states:</p>
<ul>
<li>Pending</li>
<li>Fulfilled</li>
<li>Rejected</li>
</ul>
<p>When we create a promise, it’s in a pending state. When we call the <code>resolve</code> function, it goes in a fulfilled state and if we call <code>reject</code> it will go in the rejected state.</p>
<p>To simulate the long-running or asynchronous operation, we will use the <code>setTimeout</code> function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
 <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-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span>;
  resolve(sum);
 }, <span class="hljs-number">2000</span>);
});
</code></pre>
<p>Here, we've created a promise which will resolve to the sum of <code>4</code> and <code>5</code> after a 2000ms (2 second) timeout is over.</p>
<p>To get the result of the successful promise execution, we need to register a callback using <code>.then</code> like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
 <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-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span>;
  resolve(sum);
 }, <span class="hljs-number">2000</span>);
});

promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// 9</span>
});
</code></pre>
<p>So whenever we call <code>resolve</code>, the promise will return back the value passed to the <code>resolve</code> function which we can collect using the <code>.then</code> handler.</p>
<p>If the operation is not successful, then we call the <code>reject</code> function like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
 <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-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span> + <span class="hljs-string">'a'</span>;
  <span class="hljs-keyword">if</span>(<span class="hljs-built_in">isNaN</span>(sum)) {
    reject(<span class="hljs-string">'Error while calculating sum.'</span>);
  } <span class="hljs-keyword">else</span> {
    resolve(sum);
  }
 }, <span class="hljs-number">2000</span>);
});

promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(result);
});
</code></pre>
<p>Here, if the <code>sum</code> is not a number, then we call the <code>reject</code> function with the error message. Otherwise we call the <code>resolve</code> function.</p>
<p>If you execute the above code, you will see the following output:</p>
<p><img src="https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/9adf1d42d876e2b87ef0ecfbf97b06a01c026eba/error_no_catch.png" alt="Error without catch" width="600" height="400" loading="lazy"></p>
<p>As you can see, we're getting an uncaught error message along with the message we've specified because calling <code>reject</code> function throws an error. But we have not added an error handler for catching that error.</p>
<p>To catch the error, we need to register another callback using <code>.catch</code> like this:</p>
<pre><code class="lang-js">promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(result);
}).catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
 <span class="hljs-built_in">console</span>.log(error);
});
</code></pre>
<p>You will see the following output:</p>
<p><img src="https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/9adf1d42d876e2b87ef0ecfbf97b06a01c026eba/error_catch.png" alt="Error with catch" width="600" height="400" loading="lazy"></p>
<p>As you can see, we have added the <code>.catch</code> handler, so we're not getting any uncaught error but we're just logging the error to the console.</p>
<p>This also avoids stopping your application abruptly.</p>
<p>So it's always recommended to add the <code>.catch</code> handler to every promise so your application will not stop from running because of the error.</p>
<h3 id="heading-promise-chaining">Promise chaining</h3>
<p>We can add multiple <code>.then</code> handlers to a single promise like this:</p>
<pre><code class="lang-js">promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'first .then handler'</span>);
 <span class="hljs-keyword">return</span> result;
}).then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'second .then handler'</span>);
 <span class="hljs-built_in">console</span>.log(result);
}).catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
 <span class="hljs-built_in">console</span>.log(error);
});
</code></pre>
<p>When we have multiple <code>.then</code> handlers added, the return value of the previous <code>.then</code> handler is automatically passed to the next <code>.then</code> handler.</p>
<p><img src="https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/9adf1d42d876e2b87ef0ecfbf97b06a01c026eba/promise_chaining.png" alt="Promise Chaining" width="600" height="400" loading="lazy"></p>
<p>As you can see, adding <code>4 + 5</code> resolves a promise and we get that sum in the first <code>.then</code> handler. There we're printing a log statement and returning that sum to the next <code>.then</code> handler.</p>
<p>And inside the next <code>.then</code> handler, we're adding a log statement and then we're printing the result we got from the previous <code>.then</code> handler.</p>
<p>This way of adding multiple <code>.then</code> handlers is known as promise chaining.</p>
<h3 id="heading-how-to-delay-a-promises-execution-in-javascript">How to delay a promise's execution in JavaScript</h3>
<p>Many times we don't want to create promise immediately but want to create one after some operation is completed.</p>
<p>To achieve this, we can wrap the promise in a function and return that promise from that function like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createPromise</span>(<span class="hljs-params"></span>) </span>{
 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
  <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-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span>;
   <span class="hljs-keyword">if</span>(<span class="hljs-built_in">isNaN</span>(sum)) {
     reject(<span class="hljs-string">'Error while calculating sum.'</span>);
   } <span class="hljs-keyword">else</span> {
    resolve(sum);
   }
  }, <span class="hljs-number">2000</span>);
 });
}
</code></pre>
<p>This way, we can use the function parameters inside the promise, making the function truly dynamic.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createPromise</span>(<span class="hljs-params">a, b</span>) </span>{
 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
  <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-keyword">const</span> sum = a + b;
   <span class="hljs-keyword">if</span>(<span class="hljs-built_in">isNaN</span>(sum)) {
     reject(<span class="hljs-string">'Error while calculating sum.'</span>);
   } <span class="hljs-keyword">else</span> {
    resolve(sum);
   }
  }, <span class="hljs-number">2000</span>);
 });
}

createPromise(<span class="hljs-number">1</span>,<span class="hljs-number">8</span>)
 .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">output</span>) </span>{
  <span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">// 9</span>
});

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

createPromise(<span class="hljs-number">10</span>,<span class="hljs-number">24</span>)
 .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">output</span>) </span>{
  <span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">// 34</span>
});
</code></pre>
<p><img src="https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/9adf1d42d876e2b87ef0ecfbf97b06a01c026eba/general_function.png" alt="Output" width="600" height="400" loading="lazy"></p>
<p><strong>Note:</strong> When we create a promise, it will be either resolved or rejected but not both at the same time. So we cannot add two <code>resolve</code> or <code>reject</code> function calls in the same promise.</p>
<p>Also, we can pass only a single value to the <code>resolve</code> or <code>reject</code> function.</p>
<p>If you want to pass multiple values to a <code>resolve</code> function, pass it as an object like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
 <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-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span>;
  resolve({
   <span class="hljs-attr">a</span>: <span class="hljs-number">4</span>,
   <span class="hljs-attr">b</span>: <span class="hljs-number">5</span>,
   sum
  });
 }, <span class="hljs-number">2000</span>);
});

promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(result);
}).catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
 <span class="hljs-built_in">console</span>.log(error);
});
</code></pre>
<p><img src="https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/65fba14b45b22228f49107634d440903eb0c8dbd/object_resolve.png" alt="Resolving object" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-use-arrow-functions-in-javascript">How to use arrow functions in JavaScript</h3>
<p>In all the above code examples, we've used regular ES5 function syntax while creating promises. But it's a common practice to use arrow function syntax instead of ES5 function syntax like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
 <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span> + <span class="hljs-string">'a'</span>;
  <span class="hljs-keyword">if</span>(<span class="hljs-built_in">isNaN</span>(sum)) {
    reject(<span class="hljs-string">'Error while calculating sum.'</span>);
  } <span class="hljs-keyword">else</span> {
    resolve(sum);
  }
 }, <span class="hljs-number">2000</span>);
});

promise.then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
 <span class="hljs-built_in">console</span>.log(result);
});
</code></pre>
<p>You can either use ES5 or ES6 function syntax depending on your preferences and needs.</p>
<h2 id="heading-es6-import-and-export-syntax">ES6 Import And Export Syntax</h2>
<p>Before ES6 came into play, we used multiple <code>script</code> tags in a single HTML file to import different JavaScript files like this:</p>
<pre><code class="lang-js">&lt;script type=<span class="hljs-string">"text/javascript"</span> src=<span class="hljs-string">"home.js"</span>&gt;&lt;/script&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"profile.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"user.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>So, if we had a variable with the same name in different JavaScript files, it would create a naming conflict and the value you were expecting would not be the actual value you got.</p>
<p>ES6 has fixed this issue with the concept of modules.</p>
<p>Every JavaScript file we write in ES6 is known as a module. The variables and functions we declare in each file are not available to other files until we specifically export them from that file and import them into another file.</p>
<p>So the functions and variables defined in the file are private to each file and can’t be accessed outside the file until we export them.</p>
<p>There are two types of exports:</p>
<ul>
<li>Named Exports: There can be multiple named exports in a single file</li>
<li>Default Exports: There can be only one default export in a single file</li>
</ul>
<h3 id="heading-named-exports-in-javascript">Named Exports in JavaScript</h3>
<p>To export a single value as a named export, we export it like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> temp = <span class="hljs-string">"This is some dummy text"</span>;
</code></pre>
<p>If we have multiple things to export, we can write an export statement on a separate line instead of in front of variable declaration. We specify the things to export in curly brackets.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> temp1 = <span class="hljs-string">"This is some dummy text1"</span>;
<span class="hljs-keyword">const</span> temp2 = <span class="hljs-string">"This is some dummy text2"</span>;

<span class="hljs-keyword">export</span> { temp1, temp2 };
</code></pre>
<p>Note that the export syntax is not an object literal syntax. So in ES6, to export something we can't use key-value pairs like this:</p>
<pre><code class="lang-js"> <span class="hljs-comment">// This is invalid syntax of export in ES6</span>

<span class="hljs-keyword">export</span> { <span class="hljs-attr">key1</span>: value1, <span class="hljs-attr">key2</span>: value2 }
</code></pre>
<p>To import the things we exported as a named export, we use the following syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { temp1, temp2 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./filename'</span>;
</code></pre>
<p>Note that while importing something from the file, we don't need to add the <code>.js</code> extension to the filename as it's considered by default.</p>
<pre><code class="lang-js"><span class="hljs-comment">// import from functions.js file from current directory </span>
<span class="hljs-keyword">import</span> { temp1, temp2 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./functions'</span>;

<span class="hljs-comment">// import from functions.js file from parent of current directory</span>
<span class="hljs-keyword">import</span> { temp1 } <span class="hljs-keyword">from</span> <span class="hljs-string">'../functions'</span>;
</code></pre>
<p>Here's a Code Sandbox demo: <a target="_blank" href="https://codesandbox.io/s/hardcore-pond-q4cjx">https://codesandbox.io/s/hardcore-pond-q4cjx</a></p>
<p><strong>One thing to note is that the name used while exporting has to match the name we use while importing.</strong></p>
<p>So if you are exporting as:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14159</span>;
</code></pre>
<p>then while importing you have to use the same name used while exporting:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { PI } <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p>You can't use any other name like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { PiValue } <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>; <span class="hljs-comment">// This will throw an error</span>
</code></pre>
<p>But if you already have the variable with the same name as the exported variable, you can use the renaming syntax while importing like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { PI <span class="hljs-keyword">as</span> PIValue } <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p>Here we have renamed <code>PI</code> to <code>PIValue</code> and so we can’t use the <code>PI</code> variable name now. Instead, we have to use the <code>PIValue</code> variable to get the exported value of <code>PI</code>.</p>
<p>We can also use the renaming syntax at the time of exporting:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14159</span>; 

<span class="hljs-keyword">export</span> { PI <span class="hljs-keyword">as</span> PIValue };
</code></pre>
<p>then while importing we have to use <code>PIValue</code> like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { PIValue } <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p>To export something as a named export, we have to declare it first.</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-string">'hello'</span>; <span class="hljs-comment">// this will result in error</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> greeting = <span class="hljs-string">'hello'</span>; <span class="hljs-comment">// this will work</span>
<span class="hljs-keyword">export</span> { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span> }; <span class="hljs-comment">// This will result in error</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> object = { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span> }; <span class="hljs-comment">// This will work</span>
</code></pre>
<p><strong>The order in which we import the multiple named exports is not important.</strong></p>
<p>Take a look at the below <code>validations.js</code> file:</p>
<pre><code class="lang-js"><span class="hljs-comment">// utils/validations.js</span>

<span class="hljs-keyword">const</span> isValidEmail = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">email</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/^[^@ ]+@[^@ ]+\.[^@ \.]{2,}$/</span>.test(email)) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"email is valid"</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"email is invalid"</span>;
  }
};

<span class="hljs-keyword">const</span> isValidPhone = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">phone</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/^[\\(]\d{3}[\\)]\s\d{3}-\d{4}$/</span>.test(phone)) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"phone number is valid"</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"phone number is invalid"</span>;
  }
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isEmpty</span>(<span class="hljs-params">value</span>) </span>{ 
  <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/^\s*$/</span>.test(value)) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"string is empty or contains only spaces"</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"string is not empty and does not contain spaces"</span>;
  } 
}

<span class="hljs-keyword">export</span> { isValidEmail, isValidPhone, isEmpty };
</code></pre>
<p>and in <code>index.js</code> we use these functions as shown below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>
<span class="hljs-keyword">import</span> { isEmpty, isValidEmail } <span class="hljs-keyword">from</span> <span class="hljs-string">"./utils/validations"</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"isEmpty:"</span>, isEmpty(<span class="hljs-string">"abcd"</span>)); <span class="hljs-comment">// isEmpty: string is not empty and does not contain spaces</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"isValidEmail:"</span>, isValidEmail(<span class="hljs-string">"abc@11gmail.com"</span>)); <span class="hljs-comment">// isValidEmail: email is valid</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"isValidEmail:"</span>, isValidEmail(<span class="hljs-string">"ab@c@11gmail.com"</span>)); <span class="hljs-comment">// isValidEmail: email is invalid</span>
</code></pre>
<p>Here's a Code Sandbox demo: <a target="_blank" href="https://codesandbox.io/s/youthful-flower-xesus">https://codesandbox.io/s/youthful-flower-xesus</a></p>
<p>As you can see, we can import only the required exported things and in any order, so we don’t need to check in what order we exported in another file. That’s the beauty of named exports.</p>
<h3 id="heading-default-exports-in-javascript">Default Exports in JavaScript</h3>
<p>As I said earlier, there can be at most one default export in a single file.</p>
<p>You can, however, combine multiple named exports and one default export in a single file.</p>
<p>To declare a default export we add the default keyword in front of the export keyword like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">//constants.js</span>
<span class="hljs-keyword">const</span> name = <span class="hljs-string">'David'</span>; 
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> name;
</code></pre>
<p>To import the default export we don’t add the curly brackets as we did in named export like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> name <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p>If we have multiple named exports and one default export like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14159</span>; 
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> AGE = <span class="hljs-number">30</span>;

<span class="hljs-keyword">const</span> NAME = <span class="hljs-string">"David"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> NAME;
</code></pre>
<p>then to import everything on a single line we need to use the default exported variable before the curly bracket only.</p>
<pre><code class="lang-js"><span class="hljs-comment">// NAME is default export and PI and AGE are named exports here</span>

<span class="hljs-keyword">import</span> NAME, { PI, AGE } <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p><strong>One specialty of default export is that we can change the name of the exported variable while importing:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">const</span> AGE = <span class="hljs-number">30</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AGE;
</code></pre>
<p>And in another file, we can use another name while importing</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> myAge <span class="hljs-keyword">from</span> ‘./constants’; 

<span class="hljs-built_in">console</span>.log(myAge); <span class="hljs-comment">// 30</span>
</code></pre>
<p>Here, we have changed the name of the default exported variable from <code>AGE</code> to <code>myAge</code>.</p>
<p>This works because there can be only one default export so you can name it whatever you want.</p>
<p>Another thing to note about default export is that the export default keyword cannot come before variable declaration like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">const</span> AGE = <span class="hljs-number">30</span>; <span class="hljs-comment">// This is an error and will not work</span>
</code></pre>
<p>so we have to use the export default keyword on a separate line like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js </span>

<span class="hljs-keyword">const</span> AGE = <span class="hljs-number">30</span>; 
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AGE;
</code></pre>
<p>We can, however, export default without declaring the variable like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">//constants.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
 <span class="hljs-attr">name</span>: <span class="hljs-string">"Billy"</span>,
 <span class="hljs-attr">age</span>: <span class="hljs-number">40</span>
};
</code></pre>
<p>and in another file use it like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> user <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
<span class="hljs-built_in">console</span>.log(user.name); <span class="hljs-comment">// Billy </span>
<span class="hljs-built_in">console</span>.log(user.age); <span class="hljs-comment">// 40</span>
</code></pre>
<p>There is another way of importing all the variables exported in a file using the following syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> constants <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p>Here, we are importing all the named and default exports we have in <code>constants.js</code> and stored in the <code>constants</code> variable. So, <code>constants</code> will become an object now.</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> USERNAME = <span class="hljs-string">"David"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
 <span class="hljs-attr">name</span>: <span class="hljs-string">"Billy"</span>,
 <span class="hljs-attr">age</span>: <span class="hljs-number">40</span>
};
</code></pre>
<p>And in another file, we use it as below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// test.js</span>

<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> constants <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;

<span class="hljs-built_in">console</span>.log(constants.USERNAME); <span class="hljs-comment">// David</span>
<span class="hljs-built_in">console</span>.log(constants.default); <span class="hljs-comment">// { name: "Billy", age: 40 }</span>
<span class="hljs-built_in">console</span>.log(constants.default.age); <span class="hljs-comment">// 40</span>
</code></pre>
<p>Here's a Code Sandbox demo: <a target="_blank" href="https://codesandbox.io/s/green-hill-dj43b">https://codesandbox.io/s/green-hill-dj43b</a></p>
<p>If you don’t want to export on separate lines for default and named<br>exports, you can combine it as shown below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14159</span>; <span class="hljs-keyword">const</span> AGE = <span class="hljs-number">30</span>;
<span class="hljs-keyword">const</span> USERNAME = <span class="hljs-string">"David"</span>;
<span class="hljs-keyword">const</span> USER = {
 <span class="hljs-attr">name</span>: <span class="hljs-string">"Billy"</span>,
 <span class="hljs-attr">age</span>: <span class="hljs-number">40</span> 
};

<span class="hljs-keyword">export</span> { PI, AGE, USERNAME, USER <span class="hljs-keyword">as</span> <span class="hljs-keyword">default</span> };
</code></pre>
<p>Here, we are exporting <code>USER</code> as the default export and others as named exports.</p>
<p>In another file, you can use it like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> USER, { PI, AGE, USERNAME } <span class="hljs-keyword">from</span> <span class="hljs-string">"./constants"</span>;
</code></pre>
<p>Here's a Code Sandbox demo: <a target="_blank" href="https://codesandbox.io/s/eloquent-northcutt-7btp1">https://codesandbox.io/s/eloquent-northcutt-7btp1</a></p>
<h3 id="heading-in-summary">In summary:</h3>
<ol>
<li>In ES6, data declared in one file is not accessible to another file until it is exported from that file and imported into another file.</li>
<li>If we have a single thing in a file to export like class declaration, we use default export otherwise we use named export. We can also combine default and named exports in a single file.</li>
</ol>
<h2 id="heading-default-parameters-in-javascript">Default Parameters in JavaScript</h2>
<p>ES6 has added a pretty useful feature of providing default parameters while defining functions.</p>
<p>Suppose we have an application, where once the user login into the system, we show them a welcome message like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showMessage</span>(<span class="hljs-params">firstName</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Welcome back, "</span> + firstName;
}
<span class="hljs-built_in">console</span>.log(showMessage(<span class="hljs-string">'John'</span>)); <span class="hljs-comment">// Welcome back, John</span>
</code></pre>
<p>But what if we don’t have the user name in our database as it was an optional field while registering? Then we can show the <code>Welcome Guest</code> message to the user after login.</p>
<p>So we first need to check if the <code>firstName</code> is provided and then display the corresponding message. Before ES6, we would have had to write code like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showMessage</span>(<span class="hljs-params">firstName</span>) </span>{
  <span class="hljs-keyword">if</span>(firstName) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Welcome back, "</span> + firstName;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Welcome back, Guest"</span>;
  }
}

<span class="hljs-built_in">console</span>.log(showMessage(<span class="hljs-string">'John'</span>)); <span class="hljs-comment">// Welcome back, John </span>
<span class="hljs-built_in">console</span>.log(showMessage()); <span class="hljs-comment">// Welcome back, Guest</span>
</code></pre>
<p>But now in ES6 using default function parameters we can write the above code as shown below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showMessage</span>(<span class="hljs-params">firstName = <span class="hljs-string">'Guest'</span></span>) </span>{
   <span class="hljs-keyword">return</span> <span class="hljs-string">"Welcome back, "</span> + firstName;
}

<span class="hljs-built_in">console</span>.log(showMessage(<span class="hljs-string">'John'</span>)); <span class="hljs-comment">// Welcome back, John </span>
<span class="hljs-built_in">console</span>.log(showMessage()); <span class="hljs-comment">// Welcome back, Guest</span>
</code></pre>
<p><strong>We can assign any value as a default value to the function parameter.</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">display</span>(<span class="hljs-params">a = <span class="hljs-number">10</span>, b = <span class="hljs-number">20</span>, c = b</span>) </span>{ 
 <span class="hljs-built_in">console</span>.log(a, b, c);
}

display(); <span class="hljs-comment">// 10 20 20</span>
display(<span class="hljs-number">40</span>); <span class="hljs-comment">// 40 20 20</span>
display(<span class="hljs-number">1</span>, <span class="hljs-number">70</span>); <span class="hljs-comment">// 1 70 70</span>
display(<span class="hljs-number">1</span>, <span class="hljs-number">30</span>, <span class="hljs-number">70</span>); <span class="hljs-comment">// 1 30 70</span>
</code></pre>
<p>As you can see, we have assigned unique values to a and b function parameters but for c we're assigning the value of b. So whatever value we have provided for b will be assigned to c also if there is no specific value provided for c while calling the function.</p>
<p>In the above code, we have not provided all the arguments to the function. So the above function calls will be the same as below:</p>
<pre><code class="lang-js">display(); <span class="hljs-comment">// is same as display(undefined, undefined, undefined)</span>
display(<span class="hljs-number">40</span>); <span class="hljs-comment">// is same as display(40, undefined, undefined)</span>
display(<span class="hljs-number">1</span>, <span class="hljs-number">70</span>); <span class="hljs-comment">// is same as display(1, 70, undefined)</span>
</code></pre>
<p>So if the argument passed is <code>undefined</code>, the default value will be used for the corresponding parameter.</p>
<p><strong>We can also assign complex or calculated values as a default value.</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> defaultUser = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>,
  <span class="hljs-attr">location</span>: <span class="hljs-string">'NY'</span>,
  <span class="hljs-attr">job</span>: <span class="hljs-string">'Software Developer'</span>
};

<span class="hljs-keyword">const</span> display = <span class="hljs-function">(<span class="hljs-params">user = defaultUser, age = <span class="hljs-number">60</span> / <span class="hljs-number">2</span> </span>) =&gt;</span> { 
 <span class="hljs-built_in">console</span>.log(user, age);
};
display();

<span class="hljs-comment">/* output

{
  name: 'Jane',
  location: 'NY',
  job: 'Software Developer'
} 30 

*/</span>
</code></pre>
<p>Now, take a look at the below ES5 code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 Code</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</span>(<span class="hljs-params">page, results, gender, nationality</span>) </span>{
  <span class="hljs-keyword">var</span> params = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">if</span>(page === <span class="hljs-number">0</span> || page) {
   params += <span class="hljs-string">`page=<span class="hljs-subst">${page}</span>&amp;`</span>; 
  }
  <span class="hljs-keyword">if</span>(results) {
   params += <span class="hljs-string">`results=<span class="hljs-subst">${results}</span>&amp;`</span>;
  }
  <span class="hljs-keyword">if</span>(gender) {
   params += <span class="hljs-string">`gender=<span class="hljs-subst">${gender}</span>&amp;`</span>;
  }
  <span class="hljs-keyword">if</span>(nationality) {
   params += <span class="hljs-string">`nationality=<span class="hljs-subst">${nationality}</span>`</span>;
  }

  fetch(<span class="hljs-string">'https://randomuser.me/api/?'</span> + params) 
   .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">response</span>) </span>{
     <span class="hljs-keyword">return</span> response.json(); 
   })
   .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{ 
    <span class="hljs-built_in">console</span>.log(result);
   }) 
   .catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'error'</span>, error); 
   }); 
}

getUsers(<span class="hljs-number">0</span>, <span class="hljs-number">10</span>, <span class="hljs-string">'male'</span>, <span class="hljs-string">'us'</span>);
</code></pre>
<p>In this code, we’re making an API call to the <a target="_blank" href="https://randomuser.me/">Random user</a> API by passing various optional parameters in the <code>getUsers</code> function.</p>
<p>So before making the API call, we have added various if conditions to check if the parameter is added or not, and based on that we’re constructing the query string like this: <code>https://randomuser.me/api/? page=0&amp;results=10&amp;gender=male&amp;nationality=us</code>.</p>
<p>But instead of adding so many if conditions, we can use the default parameters while defining the function parameters as shown below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</span>(<span class="hljs-params">page = <span class="hljs-number">0</span>, results = <span class="hljs-number">10</span>, gender = <span class="hljs-string">'male'</span>,nationality = <span class="hljs-string">'us'</span></span>) </span>{
 fetch(<span class="hljs-string">`https://randomuser.me/api/?page=<span class="hljs-subst">${page}</span>&amp;results=<span class="hljs-subst">${results}</span>&amp;gender=<span class="hljs-subst">${gender}</span>&amp;nationality=<span class="hljs-subst">${nationality}</span>`</span>)
 .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">response</span>) </span>{ 
  <span class="hljs-keyword">return</span> response.json();
 }) 
 .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
   <span class="hljs-built_in">console</span>.log(result); 
 })
 .catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{ 
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'error'</span>, error);
  }); 
}

getUsers();
</code></pre>
<p>As you can see, we have simplified the code a lot. So when we don’t provide any argument to the <code>getUsers</code> function, it will take default values and we can also provide our own values like this:</p>
<pre><code class="lang-js">getUsers(<span class="hljs-number">1</span>, <span class="hljs-number">20</span>, <span class="hljs-string">'female'</span>, <span class="hljs-string">'gb'</span>);
</code></pre>
<p>So it will override the default parameters of the function.</p>
<h3 id="heading-null-is-not-equal-to-undefined">null is not equal to undefined</h3>
<p>But you need to be aware of one thing: <code>null</code> and <code>undefined</code> are two different things while defining default parameters.</p>
<p>Take a look at the below code:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">display</span>(<span class="hljs-params">name = <span class="hljs-string">'David'</span>, age = <span class="hljs-number">35</span>, location = <span class="hljs-string">'NY'</span></span>)</span>{
 <span class="hljs-built_in">console</span>.log(name, age, location); 
}

display(<span class="hljs-string">'David'</span>, <span class="hljs-number">35</span>); <span class="hljs-comment">// David 35 NY</span>
display(<span class="hljs-string">'David'</span>, <span class="hljs-number">35</span>, <span class="hljs-literal">undefined</span>); <span class="hljs-comment">// David 35 NY</span>
</code></pre>
<p>As we have not provided the third value for the location parameter in the first call to display, it will be <code>undefined</code> by default so the default value of location will be used in both of the function calls. But the below function calls are not equal.</p>
<pre><code class="lang-js">display(<span class="hljs-string">'David'</span>, <span class="hljs-number">35</span>, <span class="hljs-literal">undefined</span>); <span class="hljs-comment">// David 35 NY</span>
display(<span class="hljs-string">'David'</span>, <span class="hljs-number">35</span>, <span class="hljs-literal">null</span>); <span class="hljs-comment">// David 35 null</span>
</code></pre>
<p>When we pass <code>null</code> as an argument, we’re specifically saying to assign a <code>null</code> value to the <code>location</code> parameter which is not the same as <code>undefined</code>. So it will not take the default value of <code>NY</code>.</p>
<h2 id="heading-arrayprototypeincludes">Array.prototype.includes</h2>
<p>ES7 has added a new function that checks if an element is present in the array or not and returns a boolean value of either <code>true</code> or <code>false</code>.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 Code</span>

<span class="hljs-keyword">const</span> numbers = [<span class="hljs-string">"one"</span>, <span class="hljs-string">"two"</span>, <span class="hljs-string">"three"</span>, <span class="hljs-string">"four"</span>];

<span class="hljs-built_in">console</span>.log(numbers.indexOf(<span class="hljs-string">"one"</span>) &gt; <span class="hljs-number">-1</span>); <span class="hljs-comment">// true </span>
<span class="hljs-built_in">console</span>.log(numbers.indexOf(<span class="hljs-string">"five"</span>) &gt; <span class="hljs-number">-1</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p>The same code using the Array <code>includes</code> method can be written as shown below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES7 Code</span>

<span class="hljs-keyword">const</span> numbers = [<span class="hljs-string">"one"</span>, <span class="hljs-string">"two"</span>, <span class="hljs-string">"three"</span>, <span class="hljs-string">"four"</span>];

<span class="hljs-built_in">console</span>.log(numbers.includes(<span class="hljs-string">"one"</span>)); <span class="hljs-comment">// true </span>
<span class="hljs-built_in">console</span>.log(numbers.includes(<span class="hljs-string">"five"</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>So using the Array <code>includes</code> methods makes code short and easy to understand.</p>
<p>The <code>includes</code> method also comes in handy when comparing with different values.</p>
<p>Take a look at the below code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> day = <span class="hljs-string">"monday"</span>;

<span class="hljs-keyword">if</span>(day === <span class="hljs-string">"monday"</span> || day === <span class="hljs-string">"tuesday"</span> || day === <span class="hljs-string">"wednesday"</span>) {
  <span class="hljs-comment">// do something</span>
}
</code></pre>
<p>The above code using the <code>includes</code> method can be simplified as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> day = <span class="hljs-string">"monday"</span>;

<span class="hljs-keyword">if</span>([<span class="hljs-string">"monday"</span>, <span class="hljs-string">"tuesday"</span>, <span class="hljs-string">"wednesday"</span>].includes(day)) {
  <span class="hljs-comment">// do something</span>
}
</code></pre>
<p>So the <code>includes</code> method is pretty handy when checking for values in an array.</p>
<h2 id="heading-closing-points">Closing points</h2>
<p>There are many changes that have been incorporated into JavaScript starting from ES6. And every JavaScript, Angular, React, or Vue developer should be aware of them.</p>
<p>Knowing them makes you a better developer and can even help you get a higher paying job. And if you're just learning libraries like React and frameworks like Angular and Vue, you'll certainly want to be familiar with these new features.</p>
<h2 id="heading-learn-more-about-modern-javascript-features">Learn more about Modern JavaScript features</h2>
<p>You can learn everything about the latest features added in JavaScript in my <a target="_blank" href="https://modernjavascript.yogeshchavan.dev/">Mastering Modern JavaScript</a> book. It is the only guide you need to learn modern JavaScript concepts.</p>
<p><a target="_blank" href="https://modernjavascript.yogeshchavan.dev/"><img src="https://modernjavascript.yogeshchavan.dev/book_cover.jpg" width="600" height="400" alt="book_cover" loading="lazy"></a></p>
<p>Subscribe to my <a target="_blank" href="https://bit.ly/2HwVEA2">weekly newsletter</a> to join 1000+ other subscribers to get amazing tips, tricks, and articles directly in your inbox.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 5 JavaScript Tips That'll Help You Save Time ]]>
                </title>
                <description>
                    <![CDATA[ I've always wanted to create videos around my programming hobby. But I'm not a native English speaker, and I was scared to try. But a few weeks ago, while I was preparing some JavaScript tips to start my YouTube journey, I wrote this list of time-sav... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/time-saving-javascript-tips/</link>
                <guid isPermaLink="false">66bb921bd2bda3e4315491e7</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tips ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Gaël Thomas ]]>
                </dc:creator>
                <pubDate>Thu, 19 Nov 2020 16:54:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/11/time-saving-javascript-tips.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I've always wanted to create videos around my programming hobby. But I'm not a native English speaker, and I was scared to try.</p>
<p>But a few weeks ago, while I was preparing some JavaScript tips to start my YouTube journey, I wrote this list of time-saving tips. I hope they help you as they've helped me.</p>
<p>In this article, I'm going to share with you 5 useful JavaScript tips (are you ready to dive in? 😀).</p>
<p>And now, guess what? Some of these tips are on <a target="_blank" href="https://www.youtube.com/channel/UCSRuzHhjUaAnBb6_rmlr10g">my YouTube channel</a>📹! (here is <a target="_blank" href="https://www.youtube.com/playlist?list=PL-P9AMQZdy2aj3uLhjHagEsfTOrVqF7AR">the playlist</a>. </p>
<h2 id="heading-object-destructuring">Object Destructuring</h2>
<p>Destructuring is a feature that was introduced in ES6. It's one of the features you will use daily once you know how.</p>
<p>It helps you deal with three main issues:</p>
<ul>
<li><strong>Repetition.</strong> Every time you want to extract one object property and create a new variable, you create a new line.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <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">password</span>: <span class="hljs-string">"123"</span>,
};

<span class="hljs-comment">// Wow... should we display</span>
<span class="hljs-comment">// John's password like that?</span>

<span class="hljs-keyword">const</span> firstName = user.firstName;
<span class="hljs-keyword">const</span> lastName = user.lastName;
<span class="hljs-keyword">const</span> password = user.password;
</code></pre>
<ul>
<li><strong>Accessibility.</strong> Each time you want to access an object property, you should write the path to it. (<strong>example:</strong> <code>user.firstName</code>, <code>user.family.sister</code>, and so on).</li>
<li><strong>Usage.</strong> As an example, when you create a new function, and you are only working with one property of an object.</li>
</ul>
<p>Now that you've seen what these three issues with objects are, how do you think you can solve them?</p>
<h3 id="heading-how-to-solve-the-repetition-issue">How to Solve the Repetition Issue</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <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">password</span>: <span class="hljs-string">"123"</span>,
};

<span class="hljs-keyword">const</span> { firstName, lastName, password } = user;

<span class="hljs-built_in">console</span>.log(firstName, lastName, password);
<span class="hljs-comment">// Output: 'John', 'Doe', '123'</span>
</code></pre>
<p>Destructuring is the process of extracting a property from an object by its key. By taking an existing key in your object, then placing it between two brackets (<code>{ firstName }</code>) you tell JavaScript:</p>
<p>"Hey JavaScript, I want to create a variable with the same name as my property. I want to create a variable <code>firstName</code> for the <code>firstName</code> property of my object."</p>
<blockquote>
<p><strong>Note:</strong> If you want to destructure an object, you should always use an existing key. Otherwise, it will not work.</p>
</blockquote>
<h3 id="heading-how-to-solve-the-accessibility-issue">How to Solve the Accessibility Issue</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <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">password</span>: <span class="hljs-string">"123"</span>,
  <span class="hljs-attr">family</span>: {
    <span class="hljs-attr">sister</span>: {
      <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Maria"</span>,
    },
  },
};

<span class="hljs-comment">// We access to the nested object `sister`</span>
<span class="hljs-comment">// and we extract the `firstName` property</span>
<span class="hljs-keyword">const</span> { firstName } = user.family.sister;

<span class="hljs-built_in">console</span>.log(firstName);
<span class="hljs-comment">// Output: 'Maria'</span>
</code></pre>
<p>When you work with nested objects, it can become quite repetitive and wastes a lot of time accessing the same property many times.</p>
<p>Using destructuring, in one line only, you can reduce the property path to one variable.</p>
<h3 id="heading-how-to-solve-the-usage-issue">How to Solve the Usage Issue</h3>
<p>Now that you know how to destructure an object, let me show you how to extract properties directly in your function parameter definition.</p>
<p>If you know React, you're probably already familiar with it.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserFirstName</span>(<span class="hljs-params">{ firstName }</span>) </span>{
  <span class="hljs-keyword">return</span> firstName;
}

<span class="hljs-keyword">const</span> user = {
  <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">password</span>: <span class="hljs-string">"123"</span>,
};

<span class="hljs-built_in">console</span>.log(getUserFirstName(user));
<span class="hljs-comment">// Output: 'John'</span>
</code></pre>
<p>In the above example, we have a <code>getUserFirstName</code> function, and we know that it will only use one property of our object, <code>firstName</code>.</p>
<p>Rather than passing the whole object or creating a new variable, we can destructure the object's function parameters.</p>
<h2 id="heading-how-to-merge-objects-in-es6">How to Merge Objects in ES6</h2>
<p>In programming, you often have to tackle issues with data structures. Thanks to <a target="_blank" href="https://herewecode.io/blog/spread-operator-in-javascript/">the spread operator</a> introduced in ES6, object and array manipulations are more straightforward.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <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">password</span>: <span class="hljs-string">"123"</span>,
};

<span class="hljs-keyword">const</span> userJob = {
  <span class="hljs-attr">jobName</span>: <span class="hljs-string">"Developer"</span>,
  <span class="hljs-attr">jobCountry</span>: <span class="hljs-string">"France"</span>,
  <span class="hljs-attr">jobTimePerWeekInHour</span>: <span class="hljs-string">"35"</span>,
};
</code></pre>
<p>Let's imagine that we have two objects:</p>
<ul>
<li><strong>User.</strong> An object defining general information about the user.</li>
<li><strong>UserJob.</strong> An object defining job information of the user.</li>
</ul>
<p>We want to create one object that only contains the properties of these two objects.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <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">password</span>: <span class="hljs-string">"123"</span>,
};

<span class="hljs-keyword">const</span> userJob = {
  <span class="hljs-attr">jobName</span>: <span class="hljs-string">"Developer"</span>,
  <span class="hljs-attr">jobCountry</span>: <span class="hljs-string">"France"</span>,
  <span class="hljs-attr">jobTimePerWeekInHour</span>: <span class="hljs-string">"35"</span>,
};

<span class="hljs-keyword">const</span> myNewUserObject = {
  ...user,
  ...userJob,
};

<span class="hljs-built_in">console</span>.log(myNewUserObject);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">//{</span>
<span class="hljs-comment">//  firstName: 'John',</span>
<span class="hljs-comment">//  lastName: 'Doe',</span>
<span class="hljs-comment">//  password: '123',</span>
<span class="hljs-comment">//  jobName: 'Developer',</span>
<span class="hljs-comment">//  jobCountry: 'France',</span>
<span class="hljs-comment">//  jobTimePerWeekInHour: '35'</span>
<span class="hljs-comment">//}</span>
</code></pre>
<p>Using the spread operator (<code>...</code>), we can extract all the properties of one object to another.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <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">password</span>: <span class="hljs-string">"123"</span>,
};

<span class="hljs-keyword">const</span> myNewUserObject = {
  ...user,
  <span class="hljs-comment">// We extract:</span>
  <span class="hljs-comment">// - firstName</span>
  <span class="hljs-comment">// - lastName</span>
  <span class="hljs-comment">// - password</span>
  <span class="hljs-comment">// and send them to</span>
  <span class="hljs-comment">// a new object `{}`</span>
};
</code></pre>
<h3 id="heading-how-to-merge-arrays">How to Merge Arrays</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> girlNames = [<span class="hljs-string">"Jessica"</span>, <span class="hljs-string">"Emma"</span>, <span class="hljs-string">"Amandine"</span>];
<span class="hljs-keyword">const</span> boyNames = [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Terry"</span>, <span class="hljs-string">"Alexandre"</span>];

<span class="hljs-keyword">const</span> namesWithSpreadSyntax = [...girlNames, ...boyNames];

<span class="hljs-built_in">console</span>.log(namesWithSpreadSyntax);
<span class="hljs-comment">// Output: ['Jessica', 'Emma', 'Amandine', 'John', 'Terry', 'Alexandre']</span>
</code></pre>
<p>Like objects, the spread operator (<code>...</code>) extracts all the elements from one array to another.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> girlNames = [<span class="hljs-string">"Jessica"</span>, <span class="hljs-string">"Emma"</span>, <span class="hljs-string">"Amandine"</span>];

<span class="hljs-keyword">const</span> newNewArray = [
  ...girlNames,
  <span class="hljs-comment">// We extract:</span>
  <span class="hljs-comment">// - 'Jessica'</span>
  <span class="hljs-comment">// - 'Emma'</span>
  <span class="hljs-comment">// - 'Amandine'</span>
  <span class="hljs-comment">// and send them to</span>
  <span class="hljs-comment">// a new array `[]`</span>
];
</code></pre>
<h3 id="heading-how-to-remove-array-duplicates">How to Remove Array Duplicates</h3>
<p>Because arrays are lists, you can have many items of the same value. If you want to remove duplicates in your array, you can follow one of the examples below.</p>
<p>One of them will be only one line thanks to ES6, but I let the "old" example  in there so you can compare.</p>
<h4 id="heading-how-to-remove-array-duplicates-the-old-way">How to remove array duplicates "the old way"</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> animals = [<span class="hljs-string">"owl"</span>, <span class="hljs-string">"frog"</span>, <span class="hljs-string">"canary"</span>, <span class="hljs-string">"duck"</span>, <span class="hljs-string">"duck"</span>, <span class="hljs-string">"goose"</span>, <span class="hljs-string">"owl"</span>];

<span class="hljs-keyword">const</span> uniqueAnimalsWithFilter = animals.filter(
  <span class="hljs-comment">// Parameters example: 'owl', 0, ['owl', 'frog', 'canary', 'duck', 'duck', 'goose', 'owl']</span>
  <span class="hljs-function">(<span class="hljs-params">animal, index, array</span>) =&gt;</span> array.indexOf(animal) == index
);

<span class="hljs-built_in">console</span>.log(uniqueAnimalsWithSet);
<span class="hljs-comment">// Output: ['owl', 'frog', 'canary', 'duck', 'goose']</span>
</code></pre>
<p>In the above example, we want to clean the <code>animals</code> array by removing all duplicates.</p>
<p>We can do that by using the function <code>filter</code> with <code>indexOf</code> inside it.</p>
<p>The <code>filter</code> function takes all elements of the <code>animals</code> array (<code>animals.filter</code>). Then for each occurrence it provides:</p>
<ul>
<li>the current value (<strong>example:</strong> <code>duck</code>)</li>
<li>the index (<strong>example:</strong> 0)</li>
<li>the initial array (<strong>example:</strong> the <code>animals</code> array =&gt; <code>['owl', 'frog', 'canary', 'duck', 'duck', 'goose', 'owl']</code>)</li>
</ul>
<p>We will apply <code>indexOf</code> on the original array for each occurrence and give as a parameter the <code>animal</code> variable (the current value).</p>
<p><code>indexOf</code> will return the first index of the current value (<strong>example:</strong> for 'owl' the index is 0).</p>
<p>Then inside of the filter, we compare the value of <code>indexOf</code> to the current index. If it's the same, we return <code>true</code> otherwise <code>false</code>.</p>
<p><code>filter</code> will create a new array with only the elements where the returned value was <code>true</code>.</p>
<p>So, in our case: <code>['owl', 'frog', 'canary', 'duck', 'goose']</code>.</p>
<h3 id="heading-how-to-remove-array-duplicates-the-new-way">How to remove array duplicates "the new way"</h3>
<p>Well, the "old way" is interesting to understand, but it's long and a bit hard. So let's check out the new way now: </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> animals = [<span class="hljs-string">"owl"</span>, <span class="hljs-string">"frog"</span>, <span class="hljs-string">"canary"</span>, <span class="hljs-string">"duck"</span>, <span class="hljs-string">"duck"</span>, <span class="hljs-string">"goose"</span>, <span class="hljs-string">"owl"</span>];

<span class="hljs-keyword">const</span> uniqueAnimalsWithSet = [...new <span class="hljs-built_in">Set</span>(animals)];

<span class="hljs-built_in">console</span>.log(uniqueAnimalsWithSet);
<span class="hljs-comment">// Output: ['owl', 'frog', 'canary', 'duck', 'goose']</span>
</code></pre>
<p>Let's separate out the different steps:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// 1</span>
<span class="hljs-keyword">const</span> animals = [<span class="hljs-string">"owl"</span>, <span class="hljs-string">"frog"</span>, <span class="hljs-string">"canary"</span>, <span class="hljs-string">"duck"</span>, <span class="hljs-string">"duck"</span>, <span class="hljs-string">"goose"</span>, <span class="hljs-string">"owl"</span>];

<span class="hljs-comment">// 2</span>
<span class="hljs-keyword">const</span> animalsSet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>(animals);

<span class="hljs-built_in">console</span>.log(animalsSet);
<span class="hljs-comment">// Output: Set { 'owl', 'frog', 'canary', 'duck', 'goose' }</span>

<span class="hljs-comment">// 3</span>
<span class="hljs-keyword">const</span> uniqueAnimalsWithSet = [...animalsSet];

<span class="hljs-built_in">console</span>.log(uniqueAnimalsWithSet);
<span class="hljs-comment">// Output: ['owl', 'frog', 'canary', 'duck', 'goose']</span>
</code></pre>
<p>We have an <code>animals</code> array, and we convert it into a <code>Set</code>, which is a special type of object in ES6.</p>
<p>The thing that's different about it is that it lets you create a collection of unique values.</p>
<blockquote>
<p><strong>Note:</strong> <code>Set</code> is a collection of unique values, but it's not an <code>Array</code>.</p>
</blockquote>
<p>Once we have our <code>Set</code> object with unique values, we need to convert it back to an array.</p>
<p>To do that, we use the spread operators to destructure it and send all the properties to a new <code>Array</code>.</p>
<p>Because the <code>Set</code> object has unique properties, our new array will also have unique values only.</p>
<h2 id="heading-how-to-use-ternary-operators">How to Use Ternary Operators</h2>
<p>Have you already heard about a way to write small conditions in only one line?</p>
<p>If not, it's time to remove a lot of your <code>if</code> and <code>else</code> blocks and convert them to small ternary operations.</p>
<p>Let's look at an example with <code>console.log</code> to start. The idea is to check the value of a variable and conditionally display an output.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> colour = <span class="hljs-string">"blue"</span>;

<span class="hljs-keyword">if</span> (colour === <span class="hljs-string">"blue"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`It's blue!`</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`It's not blue!`</span>);
}
</code></pre>
<p>This example is a typical case where you can use <a target="_blank" href="https://herewecode.io/blog/ternary-operator-in-javascript/">the ternary operator</a> to reduce these 5 <code>if</code> and <code>else</code> lines to only one!</p>
<p><strong>One line to rule them all!</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> colour = <span class="hljs-string">"blue"</span>;

colour === <span class="hljs-string">"blue"</span> ? <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`It's blue!`</span>) : <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`It's not blue!`</span>);
<span class="hljs-comment">// [condition] ? [if] : [else]</span>
</code></pre>
<p>Ternary operators replace <code>if</code> and <code>else</code> for small conditions.</p>
<blockquote>
<p><strong>Note:</strong> It's not recommended to create complex conditions with ternary operators because it can reduce readability.</p>
</blockquote>
<p>Below is another example that uses ternary operators, but this time in the <code>return</code> of a function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHelloToAnne</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-keyword">return</span> name === <span class="hljs-string">"Anne"</span> ? <span class="hljs-string">"Hello, Anne!"</span> : <span class="hljs-string">"It's not Anne!"</span>;
}

<span class="hljs-built_in">console</span>.log(sayHelloToAnne(<span class="hljs-string">"Anne"</span>));
<span class="hljs-comment">// Output: 'Hello, Anne!'</span>

<span class="hljs-built_in">console</span>.log(sayHelloToAnne(<span class="hljs-string">"Gael"</span>));
<span class="hljs-comment">// Output: "It's not Anne!"</span>
</code></pre>
<h2 id="heading-want-to-contribute-heres-how">Want to Contribute? Here's How.</h2>
<p>You are welcome to contribute to this GitHub repository. Any contribution is appreciated, and it will help each of us improve our JavaScript skills.
<a target="_blank" href="https://github.com/gael-thomas/javascript-awesome-tips">GitHub: JavaScript Awesome Tips</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you learned some new things about JavaScript while reading this post.</p>
<p>If you want more content like this, you can <a target="_blank" href="https://twitter.com/gaelgthomas/">follow me on Twitter</a> where I tweet about web development, self-improvement, and my journey as a full stack developer!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn the JavaScript You Need to Build Apps in this 28-Part Course ]]>
                </title>
                <description>
                    <![CDATA[ Are you struggling to figure out what JavaScript skills you need to build real-world apps? Check out this concise, example-filled course that provides the core JavaScript concepts you need to be productive with libraries like React, Angular, and Vue.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-javascript-to-build-apps/</link>
                <guid isPermaLink="false">66d037a4871ae63f179f6bb5</guid>
                
                    <category>
                        <![CDATA[ Apps ]]>
                    </category>
                
                    <category>
                        <![CDATA[ build apps ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ online courses ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Tue, 14 Jul 2020 13:00:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/07/JavaScript-You-Need-To-Know.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Are you struggling to figure out what JavaScript skills you need to build real-world apps? <a target="_blank" href="https://bit.ly/2020-js-bootcamp">Check out this concise, example-filled course</a> that provides the core JavaScript concepts you need to be productive with libraries like React, Angular, and Vue.</p>
<p>If you want to build serious web applications, <strong>the language to use is JavaScript</strong>. </p>
<p>But what JavaScript skills do you need to build apps effectively?</p>
<h2 id="heading-what-are-the-essential-javascript-skills">What Are the Essential JavaScript Skills?</h2>
<p>There are tons of courses on JavaScript available find online, but few specialize in what so many developers want to know:</p>
<p><em>What JavaScript skills are essential to building your own applications?</em></p>
<p>There is a gap between learning vanilla JavaScript and learning a library like React, Angular, and Vue for creating single-page JavaScript applications. </p>
<p>I've put together a complete course with the goal of showing you how to bridge this gap.</p>
<p>My goal is not only to teach you the skills you need while presenting real-world examples to solidify your understanding, but also to give you a new perspective. You'll find a better way of looking at your JavaScript code that will help you start thinking like a professional app developer.</p>
<p><em>Want to get started now?</em> <a target="_blank" href="https://bit.ly/2020-js-bootcamp">Take the entire course here</a>.</p>
<h2 id="heading-course-overview">Course Overview</h2>
<p>Let's take a brief tour through the course and each major section. We'll see how each section will ensure that you're taught JavaScript in the most effective, no-nonsense way possible. </p>
<p>In this course, we'll develop our skills from basic concepts to more complex ones. Even if you're an intermediate JavaScript developer, we'll cover every concept with additional depth and observations on the language that you likely haven't heard before. </p>
<h3 id="heading-variables-and-strings">Variables and Strings</h3>
<p>We'll begin with the building blocks of any JS program: variables. </p>
<p>First we'll cover declaring variables with let and const and how they are an improvement over the old var syntax. We'll learn concepts like block scoping, variable shadowing and the temporal dead zone, but also discover how these new keywords can make our code easier to process. </p>
<p>For example, why the <code>salePrice</code> variable below becomes more readable when we declare it with const instead of let or var.</p>
<p><a target="_blank" href="https://courses.reedbarger.com/courses/2020-js-bootcamp/lectures/17117784"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--nr3lU2vl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/hl8x9mfjy/image/upload/q_auto/v1/ghost-blog-images/Screen-Shot-2020-07-13-at-7.47.42-PM.png" alt="Click to access the course" width="600" height="400" loading="lazy"></a> <em>Click to watch this lecture</em></p>
<p>Because we declare the variable with as a constant, we know that it won't be assigned a different value later on. This makes our code easier to understand both for other developers and for ourselves. </p>
<p>Finally, in this section we'll touch on template literals, and how they improve strings within JavaScript in basically every way, from formatting text, to inserting dynamic values, and more.</p>
<h3 id="heading-types-and-conditionals">Types and Conditionals</h3>
<p>Next we'll touch on types and conditionals, which go hand in hand. </p>
<p>We'll first take a look at a strange (and often poorly understood) part of JavaScript called type coercion, which means how types are changed from one value to another.</p>
<p>Types can change implicitly when we write conditionals and this means we must know about truthy and falsy values, values that are subtly coerced to the boolean true and falsy, respectively. </p>
<p>We'll see how we can use truthy and falsy values to our advantage by creating shorter conditionals using the &amp;&amp; (and) and || (or) operators. This trick, known as short circuiting, is the basis of how JS libraries like React display or hide elements. </p>
<p><a target="_blank" href="https://learn.codeartistry.io/courses/2020-js-bootcamp/lectures/17117805"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--D7iXfT1y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/hl8x9mfjy/image/upload/q_auto/v1/ghost-blog-images/Screen-Shot-2020-07-13-at-7.58.41-PM.png" alt="Click to access the course" width="600" height="400" loading="lazy"></a><em>Click to watch this lecture</em></p>
<p>Then we'll see how to shorten our if-else conditionals with the ternary operator, and how they come in handy in situations when we want to conditionally set a variable's value.</p>
<h3 id="heading-functions">Functions</h3>
<p>After that, we'll dive into functions, the powerhouse of any Javascript app.</p>
<p>We'll demystify a crucial feature of functions called closures. We'll wrap our head around what a closure is by through creating our in a practical example. </p>
<p>This will enable us to see why closures are worth knowing and how they can improve our JavaScript code by keeping track of values between function calls: </p>
<p><a target="_blank" href="https://learn.codeartistry.io/courses/2020-js-bootcamp/lectures/17117780"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kAkgK88W--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-1.cloudinary.com/hl8x9mfjy/image/upload/q_auto/v1/ghost-blog-images/Screen-Shot-2020-07-13-at-8.05.34-PM.png" alt="Click to access the course" width="600" height="400" loading="lazy"></a>
<em>Click to watch this lecture</em></p>
<p>We'll cover a type of function, which you'll find in every modern Javascript app, namely, arrow functions. With arrow functions, we can greatly cut down our code as we go through all of the available tricks to making them as concise as possible. </p>
<p>Lastly, we'll touch on default values in functions and how they can make our code more reliable, especially if an expected argument isn't provided.</p>
<h3 id="heading-objects">Objects</h3>
<p>From primitive data types, we'll move onto objects. </p>
<p>Understanding essential app-building concepts like mutations and immutability isn't possible without knowing the difference between primitive types and object types in JavaScript. We'll cover this difference in detail and see firsthand why it matters for the reliability of our code. </p>
<p>We'll touch on a variety of practical patterns to more easily get our object data through object destructuring, as you see below:</p>
<p><a target="_blank" href="https://learn.codeartistry.io/courses/2020-js-bootcamp/lectures/17117800"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--WHgMYnlN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-2.cloudinary.com/hl8x9mfjy/image/upload/q_auto/v1/ghost-blog-images/Screen-Shot-2020-07-13-at-11.16.13-PM.png" alt="Click to access the course" width="600" height="400" loading="lazy"></a>
<em>Click to watch this lecture</em></p>
<p>Then after destructuring our objects, we'll see how to better assemble them. By using the object spread operator we can seamlessly merge multiple objects in an immutable fashion.</p>
<h3 id="heading-arrays">Arrays</h3>
<p>Arrays are essential for any list of data that we display in our apps and we need to know how to manipulate them with ease.</p>
<p>We'll cover how to perform actions on all elements in arrays through higher order array functions like map and filter to transform our elements or remove them from our array. </p>
<p>Additionally, we'll use methods like find to get individual elements based on certain conditions:</p>
<p><a target="_blank" href="https://learn.codeartistry.io/courses/2020-js-bootcamp/lectures/17117785"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--XsKHfHhi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/hl8x9mfjy/image/upload/q_auto/v1/ghost-blog-images/Screen-Shot-2020-07-13-at-11.25.18-PM.png" alt="Click to access the course" width="600" height="400" loading="lazy"></a>
<em>Click to watch this lecture</em></p>
<p>Then we'll cover the most important array method, reduce, and see its power to transform our array data into virtually any data type we want.</p>
<h3 id="heading-object-oriented-javascript">Object-Oriented JavaScript</h3>
<p>Next we'll get started with object-oriented programming and cover the core idea behind it that makes object oriented programming in JavaScript possible–the constructor function. </p>
<p>Constructor functions make it possible to give our objects shared behavior (functions) through something called the prototype chain. </p>
<p>Through another newer JavaScript feature called classes, we'll cover how we can easily inherit functionality through what's known as prototypical inheritance and extend our classes to share features between them. </p>
<p><a target="_blank" href="https://learn.codeartistry.io/courses/2020-js-bootcamp/lectures/17117787"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LSnOiPfV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-3.cloudinary.com/hl8x9mfjy/image/upload/q_auto/v1/ghost-blog-images/Screen-Shot-2020-07-13-at-11.27.08-PM.png" alt="Click to access the course" width="600" height="400" loading="lazy"></a>
<em>Click to watch this lecture</em></p>
<h3 id="heading-async-javascript">Async JavaScript</h3>
<p>After that we'll move on to async JavaScript, which is a necessary skill to have and understand if want to create sophisticated JavaScript programs of any kind. </p>
<p>We'll begin with a discussion of what asynchronous code is and how it was handled in the past using callback functions and how this creates problems in our code (such as 'callback hell'). </p>
<p>Fortunately, we'll fix some of the inherent problems with using callbacks through an ES6 feature called a Promise. We'll gain experience using promises in a practical way by getting familiar with the browser's Fetch API, which allows us to make HTTP requests and bring outside data into our apps.</p>
<p>Then, best of all, we'll touch on how to make our promises work and look just like synchronous code so we can easily reason about it with the help of the new async-await syntax for functions. </p>
<p><a target="_blank" href="https://learn.codeartistry.io/courses/2020-js-bootcamp/lectures/17117792"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8X1g6vDX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-4.cloudinary.com/hl8x9mfjy/image/upload/q_auto/v1/ghost-blog-images/Screen-Shot-2020-07-13-at-11.39.26-PM.png" alt="Click to access the course" width="600" height="400" loading="lazy"></a>
<em>Click to watch this lecture</em></p>
<h3 id="heading-essential-topics">Essential Topics</h3>
<p>We'll wrap up the course with some key skills necessary for starting to build complete JavaScript projects. First of all, we'll do a deep dive into ES Modules, an ES6 feature which allows us to share our JavaScript code across files.</p>
<p>We'll tackle thorny issues such as the <code>this</code> keyword by covering a list of concrete rules to follow in order to figure out it's value in any context, such as in a DOM event handler:</p>
<p><a target="_blank" href="https://learn.codeartistry.io/courses/2020-js-bootcamp/lectures/17117789"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--k1WMG7d2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res-4.cloudinary.com/hl8x9mfjy/image/upload/q_auto/v1/ghost-blog-images/Screen-Shot-2020-07-13-at-11.28.37-PM.png" alt="Click to access the course" width="600" height="400" loading="lazy"></a>
<em>Click to watch this lecture</em></p>
<p>And finally, we'll wrap up the course with a general discussion of imperative versus declarative code, which you should strive for in your coding career, and why. </p>
<h2 id="heading-watch-the-course-now">Watch the course now</h2>
<p>Take this course and, within an afternoon or two, you'll learn concepts that will meaningfully grow your JavaScript skillset and enable you to tackle high-powered front-end libraries like React, Angular, Svelte, Vue, and more with confidence. </p>
<p>Enjoy!</p>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Multiplayer Tabletop Game Simulator with Vue, Phaser, Node, Express, and Socket.IO ]]>
                </title>
                <description>
                    <![CDATA[ By M. S. Farzan Putting together all of the pieces of a full stack JavaScript application can be a complex endeavor.   In this tutorial, we're going to build a multiplayer tabletop game simulator using Vue, Phaser, Node/Express, and Socket.IO to lear... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-multiplayer-tabletop-game-simulator/</link>
                <guid isPermaLink="false">66d851eba2a6d73be8613877</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express JS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Game Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GameDev ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ phaser 3 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SocketIO ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 13 Jul 2020 23:31:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/07/How-to-Tabletop-Game-Simulator---Thumb.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By M. S. Farzan</p>
<p>Putting together all of the pieces of a full stack JavaScript application can be a complex endeavor.  </p>
<p>In this tutorial, we're going to build a multiplayer tabletop game simulator using <a target="_blank" href="https://vuejs.org/">Vue</a>, <a target="_blank" href="http://phaser.io/">Phaser</a>, <a target="_blank" href="https://nodejs.org/">Node</a>/<a target="_blank" href="https://expressjs.com/">Express</a>, and <a target="_blank" href="https://socket.io/">Socket.IO</a> to learn several concepts that will be useful in any full stack app.</p>
<p>You can follow along with this video tutorial as well (1 hour 16 minute watch):</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/laNi0fdF_DU" 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>All of the project files for this tutorial are available on <a target="_blank" href="https://github.com/sominator/tabletop-project">GitHub</a>.</p>
<h2 id="heading-project-overview">Project Overview</h2>
<p>Our project will feature a Phaser game instance that will allow us to create tokens and cards on screen, and move them around on a digital game board.</p>
<p>The Phaser instance will be wrapped in a Vue component that will handle things like multiplayer chat and commands.  Together, Phaser and Vue will comprise our front end (referred to from here on as the "client"), and we'll use Socket.IO to communicate with other players and tie together the front and back ends of our app.</p>
<p>The back end (referred to from here on as the "server") will be a simple Express server that receives Socket.IO events from the client and acts accordingly.  The whole application will run on Node as its runtime.</p>
<p>You don't need to be an expert in any of the above frameworks to complete this project, but it would be a good idea to have a solid foundation in basic JavaScript and HTML/CSS before trying to tackle the specifics. You can also follow along with my series on <a target="_blank" href="https://www.freecodecamp.org/news/learn-javascript-by-making-digital-tabletop-games-and-web-apps/">Learning JavaScript by Making Digital Tabletop Games and Web Apps</a>.  </p>
<p>You'll also want to make sure that you have Node and <a target="_blank" href="https://github.com/">Git</a> installed, along with your favorite code editor and a command line interface (you can follow my tutorial on setting up an IDE <a target="_blank" href="https://www.freecodecamp.org/news/how-to-set-up-an-integrated-development-environment-ide/">here</a> if you need help).</p>
<p>Let's get started!</p>
<h2 id="heading-part-1-client-basics">Part 1: Client Basics</h2>
<p>We'll begin building our client by installing the <a target="_blank" href="https://cli.vuejs.org/">Vue CLI</a>, which will help us with some tooling and allow us to make changes to our files without having to reload our web browser.</p>
<p>In a command line, type in the following to install the Vue CLI globally:</p>
<pre><code class="lang-cli">npm install -g @vue/cli
</code></pre>
<p>Navigate to a desired directory and create a new folder for our project:</p>
<pre><code class="lang-cli">mkdir tabletop-project
cd tabletop-project
</code></pre>
<p>Now we can use the Vue CLI to template a front end project for us:</p>
<pre><code class="lang-cli">vue create client
</code></pre>
<p>You can just hit "enter" at the ensuing prompts unless you have specific preferences.</p>
<p>The Vue CLI has helpfully templated a front end project for us, which we can view in our code editor:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/1.JPG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let's navigate to our new client folder in our CLI and run the template app:</p>
<pre><code class="lang-cli">cd client
npm run serve
</code></pre>
<p>After a little work, the Vue CLI should begin displaying our app in a web browser at the default http://localhost:8080:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/2.JPG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Cool!  We have the basic structure of our client.  Let's break it by creating two new components in the /components folder, called Game.vue and Chat.vue (you can go ahead and delete HelloWorld.vue and anything in the assets folder if you're obsessed with tidiness like I am).</p>
<p>Replace the code in App.vue with the following:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"game"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Game</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"border"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"input"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Chat</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-keyword">import</span> Chat <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Chat.vue'</span>;
    <span class="hljs-keyword">import</span> Game <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Game.vue'</span>;

    <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
        <span class="hljs-attr">name</span>: <span class="hljs-string">'App'</span>,
        <span class="hljs-attr">components</span>: {
            Chat,
            Game
        }
    }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
    <span class="hljs-selector-id">#app</span> {
        <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Trebuchet MS'</span>;
        <span class="hljs-attribute">text-align</span>: left;
        <span class="hljs-attribute">background-color</span>: black;
        <span class="hljs-attribute">color</span>: cyan;
        <span class="hljs-attribute">display</span>: flex;
    }
    <span class="hljs-selector-id">#game</span> {
        <span class="hljs-attribute">width</span>: <span class="hljs-number">50vw</span>;
        <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
    }
    <span class="hljs-selector-id">#input</span> {
        <span class="hljs-attribute">width</span>: <span class="hljs-number">50vw</span>;
        <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
    }
    <span class="hljs-selector-id">#border</span> {
        <span class="hljs-attribute">border-right</span>: <span class="hljs-number">2px</span> solid cyan;
    }
    <span class="hljs-keyword">@media</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">1000px</span>) {
        <span class="hljs-selector-id">#app</span> {
            <span class="hljs-attribute">flex-direction</span>: column;
        }
        <span class="hljs-selector-id">#game</span> {
            <span class="hljs-attribute">width</span>: <span class="hljs-number">100vw</span>;
            <span class="hljs-attribute">height</span>: <span class="hljs-number">50vh</span>;
        }
        <span class="hljs-selector-id">#input</span> {
            <span class="hljs-attribute">width</span>: <span class="hljs-number">100vw</span>;
            <span class="hljs-attribute">height</span>: <span class="hljs-number">50vh</span>;
        }
    }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
</code></pre>
<p>As you can see, a Vue component ordinarily has three sections: Template, Script, and Style, which contain any HTML, JavaScript, and CSS for that component, respectively.  We've just imported our Game and Chat components here and added a little styling to give it a cyberpunk feel when it's all up and running.</p>
<p>That's actually all that we need to do to set up our App.vue component, which will house everything else in our client.  Before we can actually do anything with it, we'll need to get our server working!</p>
<h2 id="heading-part-2-server-basics">Part 2: Server Basics</h2>
<p>At our root directory (tabletop-project, above /client), initialize a new project in a new command line interface by typing:</p>
<pre><code class="lang-cli">npm init
</code></pre>
<p>Like with our client, you can go ahead and press "enter" at the prompts unless there are specifics that you'd like to designate at this time.</p>
<p>We'll need to install Express and Socket.IO, along with <a target="_blank" href="https://nodemon.io/">Nodemon</a> to watch our server files for us and reboot as necessary:</p>
<pre><code class="lang-cli">npm install --save express socket.io nodemon
</code></pre>
<p>Let's open up the new package.json file in that root directory and add a "start" command in the "scripts" section:</p>
<pre><code class="lang-javascript">  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"start"</span>: <span class="hljs-string">"nodemon server.js"</span>
  },
</code></pre>
<p>Create a new file called server.js in this directory, and enter the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> server = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)();
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>).createServer(server);
<span class="hljs-keyword">const</span> io = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>)(http);

io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">socket</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A user connected: '</span> + socket.id);

    socket.on(<span class="hljs-string">'send'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">text</span>) </span>{
        <span class="hljs-keyword">let</span> newText = <span class="hljs-string">"&lt;"</span> + socket.id + <span class="hljs-string">"&gt; "</span> + text;
        io.emit(<span class="hljs-string">'receive'</span>, newText);
    });

    socket.on(<span class="hljs-string">'disconnect'</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">'A user disconnected: '</span> + socket.id);
    });
});

http.listen(<span class="hljs-number">3000</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">'Server started!'</span>);
});
</code></pre>
<p>Excellent!  Our simple server will now listen at http://localhost:3000, and use Socket.IO to log to the console when a user connects and disconnects, with their socket ID.</p>
<p>When the server receives a "send" event from a client, it will create a new text string that includes the socket ID of the client that emitted the event, and emit its own "receive" event to all clients with the text that it received, interpolated with the socket ID.</p>
<p>We can test the server by returning to our command line and starting it up :</p>
<pre><code class="lang-cli">npm run start
</code></pre>
<p>The command console should now display:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/3-4.JPG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Cool! Let's return to the Chat component of our client to start building out our front end functionality.</p>
<h2 id="heading-part-3-chat">Part 3: Chat</h2>
<p>Let's open a separate command line interface and navigate to the /client directory. Within that directory, install the client version of Socket.IO:</p>
<pre><code class="lang-cli">npm install --save socket.io-client
</code></pre>
<p>In /client/src/components/Chat.vue, add the following code:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"output"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>STRUCT<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">v-for</span>=<span class="hljs-string">"(text, index) in textOutput"</span> <span class="hljs-attr">:key</span>=<span class="hljs-string">"index"</span>&gt;</span>{{text}}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"input"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">"textInput"</span> <span class="hljs-attr">:placeholder</span>=<span class="hljs-string">"textInput"</span> /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Send"</span> <span class="hljs-attr">v-on:click</span>=<span class="hljs-string">"submitText"</span> /&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-keyword">import</span> io <span class="hljs-keyword">from</span> <span class="hljs-string">'socket.io-client'</span>;
    <span class="hljs-keyword">let</span> socket = io(<span class="hljs-string">'http://localhost:3000'</span>);

    <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
        <span class="hljs-attr">name</span>: <span class="hljs-string">'Chat'</span>,
        <span class="hljs-attr">data</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            <span class="hljs-keyword">return</span> {
                <span class="hljs-attr">textInput</span>: <span class="hljs-literal">null</span>,
                <span class="hljs-attr">textOutput</span>: []
            }
        },
        <span class="hljs-attr">methods</span>: {
            <span class="hljs-attr">submitText</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
                event.preventDefault();
                socket.emit(<span class="hljs-string">'send'</span>, <span class="hljs-built_in">this</span>.textInput);
            }
        },
        <span class="hljs-attr">created</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            socket.on(<span class="hljs-string">'connect'</span>, <span class="hljs-function">() =&gt;</span> {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Connected!'</span>);
            });
            socket.on(<span class="hljs-string">'receive'</span>, <span class="hljs-function">(<span class="hljs-params">text</span>) =&gt;</span> {
                <span class="hljs-built_in">this</span>.textOutput.push(text);
                <span class="hljs-built_in">this</span>.textInput = <span class="hljs-literal">null</span>;
            });
        }
    }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">style</span> <span class="hljs-attr">scoped</span>&gt;</span><span class="css">
    <span class="hljs-selector-id">#container</span> {
        <span class="hljs-attribute">text-align</span>: left;
        <span class="hljs-attribute">display</span>: flex;
        <span class="hljs-attribute">flex-direction</span>: column;
        <span class="hljs-attribute">margin-left</span>: <span class="hljs-number">1vw</span>;
        <span class="hljs-attribute">min-height</span>: <span class="hljs-number">100vh</span>;
    }
    <span class="hljs-selector-tag">h1</span> {
        <span class="hljs-attribute">text-align</span>: center;
    }
    <span class="hljs-selector-class">.hotpink</span> {
        <span class="hljs-attribute">color</span>: hotpink;
    }
    <span class="hljs-selector-id">#input</span> {
        <span class="hljs-attribute">position</span>: fixed;
        <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">95vh</span>;
    }
    <span class="hljs-selector-tag">input</span><span class="hljs-selector-attr">[type=text]</span> {
        <span class="hljs-attribute">height</span>: <span class="hljs-number">20px</span>;
        <span class="hljs-attribute">width</span>:  <span class="hljs-number">40vw</span>;
        <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid cyan;
        <span class="hljs-attribute">background-color</span>: black;
        <span class="hljs-attribute">color</span>: hotpink;
        <span class="hljs-attribute">padding-left</span>: <span class="hljs-number">1em</span>;
    }
    <span class="hljs-selector-tag">input</span><span class="hljs-selector-attr">[type=submit]</span>{
        <span class="hljs-attribute">height</span>: <span class="hljs-number">25px</span>;
        <span class="hljs-attribute">width</span>: <span class="hljs-number">5vw</span>;
        <span class="hljs-attribute">background-color</span>: black;
        <span class="hljs-attribute">color</span>: cyan;
        <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid cyan;
        <span class="hljs-attribute">margin-right</span>: <span class="hljs-number">2vw</span>;
    }
    <span class="hljs-selector-tag">input</span><span class="hljs-selector-attr">[type=submit]</span><span class="hljs-selector-pseudo">:focus</span>{
        <span class="hljs-attribute">outline</span>: none;
    }
    <span class="hljs-selector-tag">input</span><span class="hljs-selector-attr">[type=submit]</span><span class="hljs-selector-pseudo">:hover</span>{
        <span class="hljs-attribute">color</span>: hotpink;
    }
    <span class="hljs-keyword">@media</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">1000px</span>) {
        <span class="hljs-selector-id">#container</span> {
            <span class="hljs-attribute">border-left</span>: none;
            <span class="hljs-attribute">border-top</span>: <span class="hljs-number">2px</span> solid cyan;
            <span class="hljs-attribute">min-height</span>: <span class="hljs-number">50vh</span>;
        }
        <span class="hljs-selector-id">#input</span> {
            <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">43vh</span>;
        }
        <span class="hljs-selector-id">#output</span> {
            <span class="hljs-attribute">margin-right</span>: <span class="hljs-number">10vw</span>;
        }
        <span class="hljs-selector-tag">input</span><span class="hljs-selector-attr">[type=text]</span> {
            <span class="hljs-attribute">width</span>: <span class="hljs-number">60vw</span>;
        }
        <span class="hljs-selector-tag">input</span><span class="hljs-selector-attr">[type=submit]</span> {
            <span class="hljs-attribute">min-width</span>: <span class="hljs-number">10vw</span>;
        }
    }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
</code></pre>
<p>Let's examine the above from bottom to top before moving forward.  Between the </p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn JavaScript by Making Digital Tabletop Games and Web Apps ]]>
                </title>
                <description>
                    <![CDATA[ By M. S. Farzan Building 2D games can be a great way to learn JavaScript, especially when working through the basics of complex tabletop game logic. In this series, I’m going to introduce you to the basics of programming, with a focus on exposing you... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-javascript-by-making-digital-tabletop-games-and-web-apps/</link>
                <guid isPermaLink="false">66d851fbe0db794d56c01bfb</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Game Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learn to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MEVN ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MongoDB ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ phaser 3 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Vue.js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jun 2020 18:21:11 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9a51740569d1a4ca24de.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By M. S. Farzan</p>
<p>Building 2D games can be a great way to learn JavaScript, especially when working through the basics of complex tabletop game logic.</p>
<p>In this series, I’m going to introduce you to the basics of programming, with a focus on exposing you to JavaScript development best practices and frameworks. Keep in mind that the things we’re going to learn will be applicable in other programming languages as well.</p>
<p>Throughout this series, I’ll be providing an emphasis on learning to code for digital tabletop game and web development. This should be useful for roleplaying, card game, and board game developers who want to create companion apps or digital versions of their games, as well as all JavaScript newcomers.  </p>
<p>After learning JavaScript and some of the frameworks and engines that we’re going to work with, along with some practice projects and outside learning of your own, you’ll be able to:</p>
<ul>
<li>run simulations</li>
<li>make your own apps, games, and websites</li>
<li>and even develop and deploy multi-user “full stack” projects that you can share with the world.</li>
</ul>
<p>If you’re not specifically interested in digital tabletop game development, you’ll probably still find this series to be helpful. We’ll be learning core concepts that are central to game and web development that you’ll be able to apply to other programming languages and frameworks.  </p>
<p>I’m a big proponent of using digital tabletop games in learning to code. Tabletop games are great because they involve a lot of logic and complex rulesets, but not physics, vector math, animation, and that sort of thing.</p>
<p>We’ll be exploring <em>real</em> programming practices such as setting up an integrated development environment and using GitHub for source control. We'll also be taking on projects that will help you polish the skills that will be fundamental in your long-term development as a coder.</p>
<p>Start by learning the basics (Beginner Series):</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/ErxRnXhL7P8" 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>Learn more about setting up an integrated development environment (Beginner Tutorial):</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/f-JWTicIOwI" 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>Learn how to use GitHub and ES6 to create and structure your code (Intermediate Tutorial):</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/z9xz-R4iuaU" 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>Learn more about Phaser for digital tabletop game development (Intermediate Tutorial):</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/CowjRuY7VtA" 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>Learn more about Vue for digital tabletop web development (Intermediate Tutorial):</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/x9oLwdGpoX4" 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>Build a multiplayer card game with Phaser 3, Express, and Socket.IO (Advanced Project):</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/fEwAgKBgoJM" 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>Build a Multiplayer Tabletop Game Simulator with Vue, Phaser, Express, Node, and Socket.IO (Advanced Project): </p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/laNi0fdF_DU" 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>Build a full stack roleplaying game character generator with MongoDB, Express, Vue, and Node (MEVN) (Advanced Project):</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/i5XUgda08qk" 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>Learn how to deploy a full stack web app to Heroku (Advanced Project):</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/rUSjVri4I30" 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>Happy coding!</p>
<p>If you enjoyed this article, please consider <a target="_blank" href="https://www.nightpathpub.com/">checking out my games and books</a>, <a target="_blank" href="https://www.youtube.com/msfarzan?sub_confirmation=1">subscribing to my YouTube channel</a>, or <a target="_blank" href="https://discord.gg/RF6k3nB">joining the <em>Entromancy</em> Discord</a>.</p>
<p>M. S. Farzan, Ph.D. has written and worked for high-profile video game companies and editorial websites such as Electronic Arts, Perfect World Entertainment, Modus Games, and MMORPG.com, and has served as the Community Manager for games like <em>Dungeons &amp; Dragons Neverwinter</em> and <em>Mass Effect: Andromeda</em>. He is the Creative Director and Lead Game Designer of <em><a target="_blank" href="https://www.nightpathpub.com/rpg">Entromancy: A Cyberpunk Fantasy RPG</a></em> and author of <em><a target="_blank" href="http://nightpathpub.com/books">The Nightpath Trilogy</a></em>. Find M. S. Farzan on Twitter <a target="_blank" href="https://twitter.com/sominator">@sominator</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Arrow Function JavaScript Tutorial – How to Declare a JS Function with the New ES6 Syntax ]]>
                </title>
                <description>
                    <![CDATA[ By Amy Haddad You’ve probably seen arrow functions written a few different ways. //example 1 const addTwo = (num) => {return num + 2;}; //example 2 const addTwo = (num) => num + 2; //example 3 const addTwo = num => num + 2; //example 4 const addTw... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/arrow-function-javascript-tutorial-how-to-declare-a-js-function-with-the-new-es6-syntax/</link>
                <guid isPermaLink="false">66d45d97bc9760a197a10345</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learn to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 02 Jun 2020 15:38:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/05/nick-fewings-zF_pTLx_Dkg-unsplash-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Amy Haddad</p>
<p>You’ve probably seen arrow functions written a few different ways.</p>
<pre><code class="lang-JS"><span class="hljs-comment">//example 1</span>
<span class="hljs-keyword">const</span> addTwo = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {<span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;};

<span class="hljs-comment">//example 2</span>
<span class="hljs-keyword">const</span> addTwo = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> num + <span class="hljs-number">2</span>;

<span class="hljs-comment">//example 3</span>
<span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num + <span class="hljs-number">2</span>;

<span class="hljs-comment">//example 4</span>
<span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">a</span> =&gt;</span> {
 <span class="hljs-keyword">const</span> newValue = a + <span class="hljs-number">2</span>;
 <span class="hljs-keyword">return</span> newValue;
};
</code></pre>
<p>Some have parentheses around the parameters, while others don’t. Some use curly brackets and the <code>return</code> keyword, others don’t. One even spans multiple lines, while the others consist of a single line.</p>
<p>Interestingly, when we invoke the above arrow functions with the same argument we get the same result.</p>
<pre><code class="lang-JS"><span class="hljs-built_in">console</span>.log(addTwo(<span class="hljs-number">2</span>));
<span class="hljs-comment">//Result: 4</span>
</code></pre>
<p>How do you know which arrow function syntax to use? That’s what this article will uncover: how to declare an arrow function.</p>
<h2 id="heading-a-major-difference">A Major Difference</h2>
<p>Arrow functions are another—more concise—way to write function expressions. However, they don’t have their own binding to the <strong><code>this</code></strong> keyword. </p>
<pre><code class="lang-JS"><span class="hljs-comment">//Function expression</span>
<span class="hljs-keyword">const</span> addNumbers = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">number1, number2</span>) </span>{
   <span class="hljs-keyword">return</span> number1 + number2;
};

<span class="hljs-comment">//Arrow function expression</span>
<span class="hljs-keyword">const</span> addNumbers = <span class="hljs-function">(<span class="hljs-params">number1, number2</span>) =&gt;</span> number1 + number2;
</code></pre>
<p>When we invoke these functions with the same arguments we get the same result.</p>
<pre><code class="lang-JS"><span class="hljs-built_in">console</span>.log(addNumbers(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>));
<span class="hljs-comment">//Result: 3</span>
</code></pre>
<p>There's an important syntactical difference to note: arrow functions use the arrow <strong><code>=&gt;</code></strong> instead of the <strong><code>function</code></strong> keyword. There are other differences to be aware of when you write arrow functions, and that’s what we’ll explore next.</p>
<h2 id="heading-parentheses">Parentheses</h2>
<p>Some arrow functions have parentheses around the parameters and others don't.</p>
<pre><code class="lang-JS"><span class="hljs-comment">//Example with parentheses</span>
<span class="hljs-keyword">const</span> addNums = <span class="hljs-function">(<span class="hljs-params">num1, num2</span>) =&gt;</span> num1 + num2;

<span class="hljs-comment">//Example without parentheses</span>
<span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num + <span class="hljs-number">2</span>;
</code></pre>
<p>As it turns out, the number of parameters an arrow function has determines whether or not we need to include parentheses.</p>
<p>An arrow function with <strong>zero parameters</strong> requires parentheses.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> hello = <span class="hljs-function">() =&gt;</span> <span class="hljs-string">"hello"</span>;
<span class="hljs-built_in">console</span>.log(hello());
<span class="hljs-comment">//Result: "hello"</span>
</code></pre>
<p>An arrow function with <strong>one parameter</strong> does <em>not</em> require parentheses. In other words, parentheses are optional. </p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num + <span class="hljs-number">2</span>;
</code></pre>
<p>So we can add parentheses to the above example and the arrow function still works.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> addTwo = <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(addTwo(<span class="hljs-number">2</span>));
<span class="hljs-comment">//Result: 4</span>
</code></pre>
<p>An arrow function with <strong>multiple parameters</strong> requires parentheses.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> addNums = <span class="hljs-function">(<span class="hljs-params">num1, num2</span>) =&gt;</span> num1 + num2;
<span class="hljs-built_in">console</span>.log(addNums(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>));
<span class="hljs-comment">//Result: 3</span>
</code></pre>
<p>Arrow functions also support <strong>rest parameters</strong> and <strong>destructuring</strong>. Both features require parentheses.</p>
<p>This is an example of an arrow function with a <strong>rest parameter</strong>.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> nums = <span class="hljs-function">(<span class="hljs-params">first, ...rest</span>) =&gt;</span> rest;
<span class="hljs-built_in">console</span>.log(nums(<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-comment">//Result: [ 2, 3, 4 ]</span>
</code></pre>
<p>And here’s one that uses <strong>destructuring</strong>.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> location = {
   <span class="hljs-attr">country</span>: <span class="hljs-string">"Greece"</span>,
   <span class="hljs-attr">city</span>: <span class="hljs-string">"Athens"</span>
};

<span class="hljs-keyword">const</span> travel = <span class="hljs-function">(<span class="hljs-params">{city}</span>) =&gt;</span> city;

<span class="hljs-built_in">console</span>.log(travel(location));
<span class="hljs-comment">//Result: "Athens"</span>
</code></pre>
<p>To summarize: if there’s only one parameter—and you’re not using rest parameters or destructuring—then parentheses are optional. Otherwise, be sure to include them.</p>
<h2 id="heading-the-function-body">The Function Body</h2>
<p>Now that we’ve got the parentheses rules covered, let’s turn to the function body of an arrow function.</p>
<p>An arrow function body can either have a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#:~:text=An%20arrow%20function%20expression%20is,cannot%20be%20used%20as%20constructors.">“concise body” or “block body”</a>. The body type influences the syntax.</p>
<p>First, the “concise body” syntax.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">a</span> =&gt;</span> a + <span class="hljs-number">2</span>;
</code></pre>
<p>The “concise body” syntax is just that: it’s concise! We don’t use the <code>return</code> keyword or curly brackets. </p>
<p>If you have a one-line arrow function (like the example above), then the value is implicitly returned. So you can omit the <code>return</code> keyword and the curly brackets. </p>
<p>Now let’s look at “block body” syntax.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">a</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> total = a + <span class="hljs-number">2</span>;
    <span class="hljs-keyword">return</span> total;
}
</code></pre>
<p>Notice that we use <em>both</em> curly brackets and the <code>return</code> keyword in the above example. </p>
<p>You normally see this syntax when the body of the function is more than one line. And that’s a key point: wrap the body of a multi-line arrow function in curly brackets and use the <code>return</code> keyword.</p>
<h3 id="heading-objects-and-arrow-functions">Objects and Arrow Functions</h3>
<p>There’s one more syntax nuance to know about: wrap the function body in parentheses when you want to return an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">object literal expression</a>.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> f = <span class="hljs-function">() =&gt;</span> ({
 <span class="hljs-attr">city</span>:<span class="hljs-string">"Boston"</span>
})
<span class="hljs-built_in">console</span>.log(f().city)
</code></pre>
<p>Without the parentheses, we get an error.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> f = <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-attr">city</span>:<span class="hljs-string">"Boston"</span>
}
<span class="hljs-comment">//Result: error</span>
</code></pre>
<p>If you find the arrow function syntax a bit confusing, you’re not alone. It takes some time to get familiar with it. But being aware of your options and requirements are steps in that direction.</p>
<p><em>I write about learning to program and the best ways to go about it (</em><a target="_blank" href="https://amymhaddad.com/">amymhaddad.com</a>).  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Var, Let, and Const – What's the Difference? ]]>
                </title>
                <description>
                    <![CDATA[ By Sarah Chima Atuonwu A lot of shiny new features came out with ES2015 (ES6). And now, since it's 2020, it's assumed that a lot of JavaScript developers have become familiar with and have started using these features.  While this assumption might be... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/</link>
                <guid isPermaLink="false">66d460fa4a0edd9b48e83587</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ frontend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 02 Apr 2020 14:10:03 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9bd4740569d1a4ca2e24.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sarah Chima Atuonwu</p>
<p>A lot of shiny new features came out with ES2015 (ES6). And now, since it's 2020, it's assumed that a lot of JavaScript developers have become familiar with and have started using these features. </p>
<p>While this assumption might be partially true, it's still possible that some of these features remain a mystery to some devs.</p>
<p>One of the features that came with ES6 is the addition of <code>let</code> and <code>const</code>, which can be used for variable declaration. The question is, what makes them different from good ol' <code>var</code> which we've been using? If you are still not clear about this, then this article is for you.</p>
<p>In this article, we'll discuss <code>var</code>, <code>let</code> and <code>const</code>  with respect to their scope, use, and hoisting. As you read, take note of the differences between them that I'll point out.</p>
<h3 id="heading-heres-an-interactive-scrim-of-var-let-and-const">Here's an Interactive Scrim of Var, Let, and Const</h3>
<div class="embed-wrapper"><iframe src="https://scrimba.com/scrim/coede4c58a4461640298cc925?embed=freecodecamp,mini-header,no-sidebar" width="100%" height="420" title="Embedded content" loading="lazy"></iframe></div>

<h2 id="heading-var">Var</h2>
<p>Before the advent of ES6, <code>var</code> declarations ruled. There are issues associated with variables declared with <code>var</code>, though. That is why it was necessary for new ways to declare variables to emerge. First, let's get to understand <code>var</code> more before we discuss those issues.</p>
<h3 id="heading-scope-of-var">Scope of var</h3>
<p><strong>Scope</strong> essentially means where these variables are available for use. <code>var</code> declarations are globally scoped or function/locally scoped. </p>
<p>The scope is global when a <code>var</code> variable is declared outside a function. This means that any variable that is declared with <code>var</code> outside a function block is available for use in the whole window. </p>
<p><code>var</code> is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function.</p>
<p>To understand further, look at the example below.</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">var</span> greeter = <span class="hljs-string">"hey hi"</span>;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">newFunction</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">var</span> hello = <span class="hljs-string">"hello"</span>;
    }
</code></pre>
<p>Here, <code>greeter</code> is globally scoped because it exists outside a function while <code>hello</code> is function scoped. So we cannot access the variable <code>hello</code> outside of a function. So if we do this:</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">var</span> tester = <span class="hljs-string">"hey hi"</span>;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">newFunction</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">var</span> hello = <span class="hljs-string">"hello"</span>;
    }
    <span class="hljs-built_in">console</span>.log(hello); <span class="hljs-comment">// error: hello is not defined</span>
</code></pre>
<p>We'll get an error which is as a result of <code>hello</code> not being available outside the function.</p>
<h3 id="heading-var-variables-can-be-re-declared-and-updated">var variables can be re-declared and updated</h3>
<p>This means that we can do this within the same scope and won't get an error.</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">var</span> greeter = <span class="hljs-string">"hey hi"</span>;
    <span class="hljs-keyword">var</span> greeter = <span class="hljs-string">"say Hello instead"</span>;
</code></pre>
<p>and this also</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">var</span> greeter = <span class="hljs-string">"hey hi"</span>;
    greeter = <span class="hljs-string">"say Hello instead"</span>;
</code></pre>
<h3 id="heading-hoisting-of-var">Hoisting of var</h3>
<p>Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that if we do this:</p>
<pre><code class="lang-javascript">    <span class="hljs-built_in">console</span>.log (greeter);
    <span class="hljs-keyword">var</span> greeter = <span class="hljs-string">"say hello"</span>
</code></pre>
<p>it is interpreted as this:</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">var</span> greeter;
    <span class="hljs-built_in">console</span>.log(greeter); <span class="hljs-comment">// greeter is undefined</span>
    greeter = <span class="hljs-string">"say hello"</span>
</code></pre>
<p>So <code>var</code> variables are hoisted to the top of their scope and initialized with a value of <code>undefined</code>.</p>
<h3 id="heading-problem-with-var">Problem with var</h3>
<p>There's a weakness that comes with  <code>var</code>. I'll use the example below to explain:</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">var</span> greeter = <span class="hljs-string">"hey hi"</span>;
    <span class="hljs-keyword">var</span> times = <span class="hljs-number">4</span>;

    <span class="hljs-keyword">if</span> (times &gt; <span class="hljs-number">3</span>) {
        <span class="hljs-keyword">var</span> greeter = <span class="hljs-string">"say Hello instead"</span>; 
    }

    <span class="hljs-built_in">console</span>.log(greeter) <span class="hljs-comment">// "say Hello instead"</span>
</code></pre>
<p>So, since <code>times &gt; 3</code> returns true, <code>greeter</code> is redefined  to <code>"say Hello instead"</code>. While this is not a problem if you knowingly want <code>greeter</code> to be redefined, it becomes a problem when you do not realize that a variable <code>greeter</code> has already been defined before.</p>
<p>If you have used <code>greeter</code> in other parts of your code, you might be surprised at the output you might get. This will likely cause a lot of bugs in your code. This is why <code>let</code> and <code>const</code> are necessary.</p>
<h2 id="heading-let">Let</h2>
<p><code>let</code> is now preferred for variable declaration. It's no surprise as it comes as an improvement to <code>var</code> declarations. It also solves the problem with <code>var</code> that we just covered. Let's consider why this is so.</p>
<h3 id="heading-let-is-block-scoped">let is block scoped</h3>
<p>A block is a chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block. </p>
<p>So a variable declared in a block with <code>let</code>  is only available for use within that block. Let me explain this with an example:</p>
<pre><code class="lang-javascript">   <span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"say Hi"</span>;
   <span class="hljs-keyword">let</span> times = <span class="hljs-number">4</span>;

   <span class="hljs-keyword">if</span> (times &gt; <span class="hljs-number">3</span>) {
        <span class="hljs-keyword">let</span> hello = <span class="hljs-string">"say Hello instead"</span>;
        <span class="hljs-built_in">console</span>.log(hello);<span class="hljs-comment">// "say Hello instead"</span>
    }
   <span class="hljs-built_in">console</span>.log(hello) <span class="hljs-comment">// hello is not defined</span>
</code></pre>
<p>We see that using <code>hello</code> outside its block (the curly braces where it was defined) returns an error. This is because <code>let</code> variables are block scoped .</p>
<h3 id="heading-let-can-be-updated-but-not-re-declared">let can be updated but not re-declared.</h3>
<p>Just like <code>var</code>,  a variable declared with <code>let</code> can be updated within its scope. Unlike <code>var</code>, a <code>let</code> variable cannot be re-declared within its scope. So while this will work:</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"say Hi"</span>;
    greeting = <span class="hljs-string">"say Hello instead"</span>;
</code></pre>
<p>this will return an error:</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"say Hi"</span>;
    <span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"say Hello instead"</span>; <span class="hljs-comment">// error: Identifier 'greeting' has already been declared</span>
</code></pre>
<p>However, if the same variable is defined in different scopes, there will be no error:</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"say Hi"</span>;
    <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
        <span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"say Hello instead"</span>;
        <span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// "say Hello instead"</span>
    }
    <span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// "say Hi"</span>
</code></pre>
<p>Why is there no error? This is because both instances are treated as different variables since they have different scopes.</p>
<p>This fact makes <code>let</code> a better choice than <code>var</code>. When using <code>let</code>, you don't have to bother if you have used a name for a variable before as a variable exists only within its scope. </p>
<p>Also, since a variable cannot be declared more than once within a scope, then the problem discussed earlier that occurs with <code>var</code> does not happen.</p>
<h3 id="heading-hoisting-of-let">Hoisting of let</h3>
<p>Just like  <code>var</code>, <code>let</code> declarations are hoisted to the top. Unlike <code>var</code> which is initialized as <code>undefined</code>, the <code>let</code> keyword is not initialized. So if you try to use a <code>let</code> variable before declaration, you'll get a <code>Reference Error</code>.</p>
<h2 id="heading-const">Const</h2>
<p>Variables declared with the <code>const</code> maintain constant values. <code>const</code> declarations share some similarities with <code>let</code> declarations.</p>
<h3 id="heading-const-declarations-are-block-scoped">const declarations are block scoped</h3>
<p>Like <code>let</code> declarations, <code>const</code> declarations can only be accessed within the block they were declared.</p>
<h3 id="heading-const-cannot-be-updated-or-re-declared">const cannot be updated or re-declared</h3>
<p>This means that the value of a variable declared with <code>const</code> remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with <code>const</code>, we can neither do this:</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> greeting = <span class="hljs-string">"say Hi"</span>;
    greeting = <span class="hljs-string">"say Hello instead"</span>;<span class="hljs-comment">// error: Assignment to constant variable.</span>
</code></pre>
<p>nor this:</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> greeting = <span class="hljs-string">"say Hi"</span>;
    <span class="hljs-keyword">const</span> greeting = <span class="hljs-string">"say Hello instead"</span>;<span class="hljs-comment">// error: Identifier 'greeting' has already been declared</span>
</code></pre>
<p>Every <code>const</code> declaration, therefore, must be initialized at the time of declaration.</p>
<p>This behavior is somehow different when it comes to objects declared with <code>const</code>. While a <code>const</code> object cannot be updated, the properties of this objects can be updated. Therefore, if we declare a <code>const</code> object as this:</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> greeting = {
        <span class="hljs-attr">message</span>: <span class="hljs-string">"say Hi"</span>,
        <span class="hljs-attr">times</span>: <span class="hljs-number">4</span>
    }
</code></pre>
<p>while we cannot do this:</p>
<pre><code class="lang-javascript">    greeting = {
        <span class="hljs-attr">words</span>: <span class="hljs-string">"Hello"</span>,
        <span class="hljs-attr">number</span>: <span class="hljs-string">"five"</span>
    } <span class="hljs-comment">// error:  Assignment to constant variable.</span>
</code></pre>
<p>we can do this:</p>
<pre><code class="lang-javascript">    greeting.message = <span class="hljs-string">"say Hello instead"</span>;
</code></pre>
<p>This will update the value of <code>greeting.message</code> without returning errors.</p>
<h3 id="heading-hoisting-of-const">Hoisting of const</h3>
<p>Just like <code>let</code>, <code>const</code> declarations are hoisted to the top but are not initialized.</p>
<p>So just in case you missed the differences, here they are:</p>
<ul>
<li><code>var</code> declarations are globally scoped or function scoped while <code>let</code> and <code>const</code> are block scoped.</li>
<li><code>var</code> variables can be updated and re-declared within its scope; <code>let</code> variables can be updated but not re-declared; <code>const</code> variables can neither be updated nor re-declared.</li>
<li>They are all hoisted to the top of their scope. But while <code>var</code> variables are initialized with <code>undefined</code>, <code>let</code> and <code>const</code> variables are not initialized.</li>
<li>While <code>var</code> and <code>let</code> can be declared without being initialized, <code>const</code> must be initialized during declaration.</li>
</ul>
<p>That's all. Got any question or additions? Please let me know.</p>
<p>Thank you for reading :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Multiplayer Card Game with Phaser 3, Express, and Socket.IO ]]>
                </title>
                <description>
                    <![CDATA[ By M. S. Farzan I'm a tabletop game developer, and am continually looking for ways to digitize game experiences.  In this tutorial, we're going to build a multiplayer card game using Phaser 3, Express, and Socket.IO. In terms of prerequisites, you'll... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-multiplayer-card-game-with-phaser-3-express-and-socket-io/</link>
                <guid isPermaLink="false">66d851e78da7a7c34f4c9223</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express JS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Game Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GameDev ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ phaser 3 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SocketIO ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 25 Mar 2020 20:57:51 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/03/Client-2-2.PNG" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By M. S. Farzan</p>
<p>I'm a <a target="_blank" href="https://www.nightpathpub.com/entromancy">tabletop game</a> developer, and am continually looking for ways to digitize game experiences.  In this tutorial, we're going to build a multiplayer card game using <a target="_blank" href="http://phaser.io/">Phaser 3</a>, <a target="_blank" href="https://expressjs.com/">Express</a>, and <a target="_blank" href="https://socket.io/">Socket.IO</a>.</p>
<p>In terms of prerequisites, you'll want to make sure that you have <a target="_blank" href="https://nodejs.org/en/">Node</a>/<a target="_blank" href="https://www.npmjs.com/">NPM</a> and <a target="_blank" href="https://github.com/">Git</a> installed and configured on your machine.  Some experience with JavaScript would be helpful, and you may want to run through the <a target="_blank" href="http://phaser.io/tutorials/making-your-first-phaser-3-game">basic Phaser tutorial</a> before tackling this one.</p>
<p>Major kudos to Scott Westover for <a target="_blank" href="https://gamedevacademy.org/create-a-basic-multiplayer-game-in-phaser-3-with-socket-io-part-1/">his tutorial on the topic</a>, Kal_Torak and the Phaser community for answering all my questions, and my good friend Mike for helping me conceptualize the architecture of this project.</p>
<p>Note: we'll be using assets and colors from my tabletop card game, <em><a target="_blank" href="https://www.nightpathpub.com/hacker-battles">Entromancy: Hacker Battles</a></em>.  If you prefer, you can use your own images (or even <a target="_blank" href="http://phaser.io/examples/v3/view/game-objects/shapes/rectangle">Phaser rectangles</a>) and colors, and you can access the entire project code on <a target="_blank" href="https://github.com/sominator/multiplayer-card-project">GitHub</a>.</p>
<p>If you'd prefer a more visual tutorial, you can also follow along with the companion video to this article:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/fEwAgKBgoJM" 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>Let's get started!</p>
<h2 id="heading-the-game">The Game</h2>
<p>Our simple card game will feature a Phaser client that will handle most of the game logic and doing things like dealing cards, providing drag-and-drop functionality, and so on.</p>
<p>On the back end, we'll spin up an Express server that will utilize Socket.IO to communicate between clients and make it so that when one player plays a card, it shows up in another player's client, and vice-versa.</p>
<p>Our goal for this project is to create a basic framework for a multiplayer card game that you can build upon and adjust to suit your own game's logic.</p>
<p>First, let's tackle the client!</p>
<h2 id="heading-the-client">The Client</h2>
<p>To scaffold our client, we're going to clone the semi-official Phaser 3 Webpack Project Template on <a target="_blank" href="https://github.com/photonstorm/phaser3-project-template">GitHub</a>.</p>
<p>Open your favorite command line interface and create a new folder:</p>
<pre><code class="lang-cli">mkdir multiplayer-card-project
cd multiplayer-card-project
</code></pre>
<p>Clone the git project:</p>
<pre><code class="lang-cli">git clone https://github.com/photonstorm/phaser3-project-template.git
</code></pre>
<p>This command will download the template in a folder called "phaser3-project-template" within /multiplayer-card-project.  If you want to follow along with our tutorial's file structure, go ahead and change that template folder's name to "client."</p>
<p>Navigate into that new directory and install all dependencies:</p>
<pre><code class="lang-cli">cd client
npm install
</code></pre>
<p>Your project folder structure should look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/File-Structure-1-4.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Before we muck with the files, let's go back to our CLI and enter the following command in the /client folder:</p>
<pre><code class="lang-cli">npm start
</code></pre>
<p>Our Phaser template utilizes Webpack to spin up a local server that in turn serves up a simple game app in our browser (usually at http://localhost:8080).  Neat!</p>
<p>Let's open our project in your favorite code editor and make some changes to fit our card game.  Delete everything in /client/src/assets and replace them with the card images from <a target="_blank" href="https://github.com/sominator/multiplayer-card-project/tree/master/client/src/assets">GitHub</a>.</p>
<p>In the /client/src directory, add a folder called "scenes" and another called "helpers."</p>
<p>In /client/src/scenes, add an empty file called "game.js".</p>
<p>In /client/src/helpers, add three empty files: "card.js", "dealer.js", and "zone.js".</p>
<p>Your project structure should now look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/File-Structure-2.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Cool!  Your client might be throwing you errors because we deleted some things, but not to worry.  Open /src/index.js, which is the main entry point to our front end app. Enter the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Phaser <span class="hljs-keyword">from</span> <span class="hljs-string">"phaser"</span>;
<span class="hljs-keyword">import</span> Game <span class="hljs-keyword">from</span> <span class="hljs-string">"./scenes/game"</span>;

<span class="hljs-keyword">const</span> config = {
    <span class="hljs-attr">type</span>: Phaser.AUTO,
    <span class="hljs-attr">parent</span>: <span class="hljs-string">"phaser-example"</span>,
    <span class="hljs-attr">width</span>: <span class="hljs-number">1280</span>,
    <span class="hljs-attr">height</span>: <span class="hljs-number">780</span>,
    <span class="hljs-attr">scene</span>: [
        Game
    ]
};

<span class="hljs-keyword">const</span> game = <span class="hljs-keyword">new</span> Phaser.Game(config);
</code></pre>
<p>All we've done here is restructure the boilerplate to utilize Phaser's "scene" system so that we can separate our game scenes rather than try to cram everything in one file.  Scenes can be useful if you're creating multiple game worlds, building things like instruction screens, or generally trying to keep things tidy.</p>
<p>Let's move to /src/scenes/game.js and write some code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Game</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Phaser</span>.<span class="hljs-title">Scene</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">super</span>({
            <span class="hljs-attr">key</span>: <span class="hljs-string">'Game'</span>
        });
    }

    preload() {
        <span class="hljs-built_in">this</span>.load.image(<span class="hljs-string">'cyanCardFront'</span>, <span class="hljs-string">'src/assets/CyanCardFront.png'</span>);
        <span class="hljs-built_in">this</span>.load.image(<span class="hljs-string">'cyanCardBack'</span>, <span class="hljs-string">'src/assets/CyanCardBack.png'</span>);
        <span class="hljs-built_in">this</span>.load.image(<span class="hljs-string">'magentaCardFront'</span>, <span class="hljs-string">'src/assets/MagentaCardFront.png'</span>);
        <span class="hljs-built_in">this</span>.load.image(<span class="hljs-string">'magentaCardBack'</span>, <span class="hljs-string">'src/assets/MagentaCardBack.png'</span>);
    }

    create() {
        <span class="hljs-built_in">this</span>.dealText = <span class="hljs-built_in">this</span>.add.text(<span class="hljs-number">75</span>, <span class="hljs-number">350</span>, [<span class="hljs-string">'DEAL CARDS'</span>]).setFontSize(<span class="hljs-number">18</span>).setFontFamily(<span class="hljs-string">'Trebuchet MS'</span>).setColor(<span class="hljs-string">'#00ffff'</span>).setInteractive();
    }

    update() {

    }
}
</code></pre>
<p>We're taking advantage of <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-github-and-es6-features-to-create-and-structure-your-code/">ES6 classes</a> to create a new Game scene, which incorporates preload(), create() and update() functions.</p>
<p>preload() is used to...well...preload any assets that we'll be using for our game.</p>
<p>create() is run when the game starts up, and where we'll be establishing much of our user interface and game logic.</p>
<p>update() is called once per frame, and we won't be making use of it in our tutorial (but it may be useful in your own game depending on its requirements).</p>
<p>Within the create() function, we've created a bit of text that says "DEAL CARDS" and set it to be interactive:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Deal-Cards.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Very cool.  Let's create a bit of placeholder code to understand how we want this whole thing to work once it's up and running.  Add the following to your create() function:</p>
<pre><code class="lang-javascript">        <span class="hljs-keyword">let</span> self = <span class="hljs-built_in">this</span>;

        <span class="hljs-built_in">this</span>.card = <span class="hljs-built_in">this</span>.add.image(<span class="hljs-number">300</span>, <span class="hljs-number">300</span>, <span class="hljs-string">'cyanCardFront'</span>).setScale(<span class="hljs-number">0.3</span>, <span class="hljs-number">0.3</span>).setInteractive();
        <span class="hljs-built_in">this</span>.input.setDraggable(<span class="hljs-built_in">this</span>.card);

        <span class="hljs-built_in">this</span>.dealCards = <span class="hljs-function">() =&gt;</span> {

        }

        <span class="hljs-built_in">this</span>.dealText.on(<span class="hljs-string">'pointerdown'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            self.dealCards();
        })

        <span class="hljs-built_in">this</span>.dealText.on(<span class="hljs-string">'pointerover'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            self.dealText.setColor(<span class="hljs-string">'#ff69b4'</span>);
        })

        <span class="hljs-built_in">this</span>.dealText.on(<span class="hljs-string">'pointerout'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            self.dealText.setColor(<span class="hljs-string">'#00ffff'</span>);
        })

        <span class="hljs-built_in">this</span>.input.on(<span class="hljs-string">'drag'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">pointer, gameObject, dragX, dragY</span>) </span>{
            gameObject.x = dragX;
            gameObject.y = dragY;
        })
</code></pre>
<p>We've added a lot of structure, but not much has happened.  Now, when our mouse hovers over the "DEAL CARDS" text, it's highlighted in cyberpunk hot pink, and there's a random card on our screen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Card.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We've placed the image at the (x, y) coordinates of (300, 300), set its scale to be a bit smaller, and made it interactive and draggable.  We've also added a little bit of logic to determine what should happen when dragged: it should follow the (x, y) coordinates of our mouse.</p>
<p>We've also created an empty dealCards() function that will be called when we click on our "DEAL CARDS" text.  Additionally, we've saved "this" - meaning the scene in which we're currently working - into a variable called "self" so that we can use it throughout our functions without worrying about scope.</p>
<p>Our Game scene is going to get messy fast if we don't start moving things around, so let's delete the code block that begins with "this.card" and move to /src/helpers/card.js to write:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Card</span> </span>{
    <span class="hljs-keyword">constructor</span>(scene) {
        <span class="hljs-built_in">this</span>.render = <span class="hljs-function">(<span class="hljs-params">x, y, sprite</span>) =&gt;</span> {
            <span class="hljs-keyword">let</span> card = scene.add.image(x, y, sprite).setScale(<span class="hljs-number">0.3</span>, <span class="hljs-number">0.3</span>).setInteractive();
            scene.input.setDraggable(card);
            <span class="hljs-keyword">return</span> card;
        }
    }
}
</code></pre>
<p>We've created a new class that accepts a scene as a parameter, and features a render() function that accepts (x, y) coordinates and a sprite.  Now, we can call this function from elsewhere and pass it the necessary parameters to create cards.</p>
<p>Let's import the card at the top of our Game scene:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Card <span class="hljs-keyword">from</span> <span class="hljs-string">'../helpers/card'</span>;
</code></pre>
<p> And enter the following code within our empty dealCards() function:</p>
<pre><code class="lang-javascript">        <span class="hljs-built_in">this</span>.dealCards = <span class="hljs-function">() =&gt;</span> {
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) {
                <span class="hljs-keyword">let</span> playerCard = <span class="hljs-keyword">new</span> Card(<span class="hljs-built_in">this</span>);
                playerCard.render(<span class="hljs-number">475</span> + (i * <span class="hljs-number">100</span>), <span class="hljs-number">650</span>, <span class="hljs-string">'cyanCardFront'</span>);
            }
        }
</code></pre>
<p>When we click on the "DEAL CARDS" button, we now iterate through a for loop that creates cards and renders them sequentially on screen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Cards.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>NICE.  We can drag those cards around the screen, but it might be nice to limit where they can be dropped to support our game logic.</p>
<p>Let's move over to /src/helpers/zone.js and add a new class:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Zone</span> </span>{
    <span class="hljs-keyword">constructor</span>(scene) {
        <span class="hljs-built_in">this</span>.renderZone = <span class="hljs-function">() =&gt;</span> {
            <span class="hljs-keyword">let</span> dropZone = scene.add.zone(<span class="hljs-number">700</span>, <span class="hljs-number">375</span>, <span class="hljs-number">900</span>, <span class="hljs-number">250</span>).setRectangleDropZone(<span class="hljs-number">900</span>, <span class="hljs-number">250</span>);
            dropZone.setData({ <span class="hljs-attr">cards</span>: <span class="hljs-number">0</span> });
            <span class="hljs-keyword">return</span> dropZone;
        };
        <span class="hljs-built_in">this</span>.renderOutline = <span class="hljs-function">(<span class="hljs-params">dropZone</span>) =&gt;</span> {
            <span class="hljs-keyword">let</span> dropZoneOutline = scene.add.graphics();
            dropZoneOutline.lineStyle(<span class="hljs-number">4</span>, <span class="hljs-number">0xff69b4</span>);
            dropZoneOutline.strokeRect(dropZone.x - dropZone.input.hitArea.width / <span class="hljs-number">2</span>, dropZone.y - dropZone.input.hitArea.height / <span class="hljs-number">2</span>, dropZone.input.hitArea.width, dropZone.input.hitArea.height)
        }
    }
}
</code></pre>
<p>Phaser has built-in dropzones that allow us to dictate where game objects can be dropped, and we've set up one here and provided it with an outline.  We've also added a tiny bit of data called "cards" to the dropzone that we'll use later.</p>
<p>Let's import our new zone into the Game scene:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Zone <span class="hljs-keyword">from</span> <span class="hljs-string">'../helpers/zone'</span>;
</code></pre>
<p> And call it in within the create() function:</p>
<pre><code class="lang-javascript">        <span class="hljs-built_in">this</span>.zone = <span class="hljs-keyword">new</span> Zone(<span class="hljs-built_in">this</span>);
        <span class="hljs-built_in">this</span>.dropZone = <span class="hljs-built_in">this</span>.zone.renderZone();
        <span class="hljs-built_in">this</span>.outline = <span class="hljs-built_in">this</span>.zone.renderOutline(<span class="hljs-built_in">this</span>.dropZone);
</code></pre>
<p>Not too shabby!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Zone.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We need to add a bit of logic to determine how cards should be dropped into the zone.  Let's do that below the "this.input.on('drag')" function:</p>
<pre><code class="lang-javascript">        <span class="hljs-built_in">this</span>.input.on(<span class="hljs-string">'dragstart'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">pointer, gameObject</span>) </span>{
            gameObject.setTint(<span class="hljs-number">0xff69b4</span>);
            self.children.bringToTop(gameObject);
        })

        <span class="hljs-built_in">this</span>.input.on(<span class="hljs-string">'dragend'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">pointer, gameObject, dropped</span>) </span>{
            gameObject.setTint();
            <span class="hljs-keyword">if</span> (!dropped) {
                gameObject.x = gameObject.input.dragStartX;
                gameObject.y = gameObject.input.dragStartY;
            }
        })

        <span class="hljs-built_in">this</span>.input.on(<span class="hljs-string">'drop'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">pointer, gameObject, dropZone</span>) </span>{
            dropZone.data.values.cards++;
            gameObject.x = (dropZone.x - <span class="hljs-number">350</span>) + (dropZone.data.values.cards * <span class="hljs-number">50</span>);
            gameObject.y = dropZone.y;
            gameObject.disableInteractive();
        })
</code></pre>
<p>Starting at the bottom of the code, when a card is dropped, we increment the "cards" data value on the dropzone, and assign the (x, y) coordinates of the card to the dropzone based on how many cards are already on it.  We also disable interactivity on cards after they're dropped so that they can't be retracted:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Zone-Dropped.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We've also made it so that our cards have a different tint when dragged, and if they're not dropped over the dropzone, they'll return to their starting positions.</p>
<p>Although our client isn't quite complete, we've done as much as we can before implementing the back end.  We can now deal cards, drag them around the screen, and drop them in a dropzone. But to move forward, we'll need to set up a server than can coordinate our multiplayer functionality.</p>
<h2 id="heading-the-server">The Server</h2>
<p>Let's open up a new command line at our root directory (above /client) and type:</p>
<pre><code class="lang-cli">npm init
npm install --save express socket.io nodemon
</code></pre>
<p>We've initialized a new package.json and installed Express, Socket.IO, and <a target="_blank" href="https://nodemon.io/">Nodemon</a> (which will watch our server and restart it upon changes).</p>
<p>In our code editor, let's change the "scripts" section of our package.json to say:</p>
<pre><code class="lang-javascript">  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"start"</span>: <span class="hljs-string">"nodemon server.js"</span>
  },
</code></pre>
<p>Excellent.  We're ready to put our server together!  Create an empty file called "server.js" in our root directory and enter the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> server = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)();
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>).createServer(server);
<span class="hljs-keyword">const</span> io = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>)(http);

io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">socket</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A user connected: '</span> + socket.id);

    socket.on(<span class="hljs-string">'disconnect'</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">'A user disconnected: '</span> + socket.id);
    });
});

http.listen(<span class="hljs-number">3000</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">'Server started!'</span>);
});
</code></pre>
<p>We're importing Express and Socket.IO, asking for the server to listen on port 3000. When a client connects to or disconnects from that port, we'll log the event to the console with the client's socket id.</p>
<p>Open a new command line interface and start the server:</p>
<pre><code class="lang-cli">npm run start
</code></pre>
<p>Our server should now be running on localhost:3000, and Nodemon will watch our back end files for any changes.  Not much else will happen except for the console log that the "Server started!"</p>
<p>In our other open command line interface, let's navigate back to our /client directory and install the client version of Socket.IO:</p>
<pre><code class="lang-cli">cd client
npm install --save socket.io-client
</code></pre>
<p>We can now import it in our Game scene:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> io <span class="hljs-keyword">from</span> <span class="hljs-string">'socket.io-client'</span>;
</code></pre>
<p>Great!  We've just about wired up our front and back ends.  All we need to do is write some code in the create() function:</p>
<pre><code class="lang-javascript">        <span class="hljs-built_in">this</span>.socket = io(<span class="hljs-string">'http://localhost:3000'</span>);

        <span class="hljs-built_in">this</span>.socket.on(<span class="hljs-string">'connect'</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">'Connected!'</span>);
        });
</code></pre>
<p>We're initializing a new "socket" variable that points to our local port 3000 and logs to the browser console upon connection.</p>
<p>Open and close a couple of browsers at http://localhost:8080 (where our Phaser client is being served) and you should see the following in your command line interface:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Console.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>YAY.  Let's start adding logic to our server.js file that will serve the needs of our card game.  Replace the existing code with the following:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> server = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)();
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>).createServer(server);
<span class="hljs-keyword">const</span> io = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>)(http);
<span class="hljs-keyword">let</span> players = [];

io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">socket</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A user connected: '</span> + socket.id);

    players.push(socket.id);

    <span class="hljs-keyword">if</span> (players.length === <span class="hljs-number">1</span>) {
        io.emit(<span class="hljs-string">'isPlayerA'</span>);
    };

    socket.on(<span class="hljs-string">'dealCards'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        io.emit(<span class="hljs-string">'dealCards'</span>);
    });

    socket.on(<span class="hljs-string">'cardPlayed'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">gameObject, isPlayerA</span>) </span>{
        io.emit(<span class="hljs-string">'cardPlayed'</span>, gameObject, isPlayerA);
    });

    socket.on(<span class="hljs-string">'disconnect'</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">'A user disconnected: '</span> + socket.id);
        players = players.filter(<span class="hljs-function"><span class="hljs-params">player</span> =&gt;</span> player !== socket.id);
    });
});

http.listen(<span class="hljs-number">3000</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">'Server started!'</span>);
});
</code></pre>
<p>We've initialized an empty array called "players" and add a socket id to it every time a client connects to the server, while also deleting the socket id upon disconnection.</p>
<p>If a client is the first to connect to the server, we ask Socket.IO to "<a target="_blank" href="https://socket.io/get-started/chat/#Emitting-events">emit</a>" an event that they're going to be Player A.  Subsequently, when the server receives an event called "dealCards" or "cardPlayed", it should emit back to the clients that they should update accordingly.</p>
<p>Believe it or not, that's all the code we need to get our server working!  Let's turn our attention back to the Game scene.  Right at the top of the create() function, type the following:</p>
<pre><code class="lang-javascript">        <span class="hljs-built_in">this</span>.isPlayerA = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.opponentCards = [];
</code></pre>
<p>Under the code block that starts with "this.socket.on(connect)", write:</p>
<pre><code class="lang-javascript">        <span class="hljs-built_in">this</span>.socket.on(<span class="hljs-string">'isPlayerA'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            self.isPlayerA = <span class="hljs-literal">true</span>;
        })
</code></pre>
<p>Now, if our client is the first to connect to the server, the server will emit an event that tells the client that it will be Player A.  The client socket receives that event and turns our "isPlayerA" boolean from false to true.</p>
<p>Note: from this point forward, you may need to reload your browser page (set to http://localhost:8080), rather than having Webpack do it automatically for you, for the client to correctly disconnect from and reconnect to the server.</p>
<p>We need to reconfigure our dealCards() logic to support the multiplayer aspect of our game, given that we want the client to deal us a certain set of cards that may be different from our opponent's.  Additionally, we want to render the backs of our opponent's cards on our screen, and vice versa.</p>
<p>We'll move to the empty /src/helpers/dealer.js file, import card.js, and create a new class:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Card <span class="hljs-keyword">from</span> <span class="hljs-string">'./card'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dealer</span> </span>{
    <span class="hljs-keyword">constructor</span>(scene) {
        <span class="hljs-built_in">this</span>.dealCards = <span class="hljs-function">() =&gt;</span> {
            <span class="hljs-keyword">let</span> playerSprite;
            <span class="hljs-keyword">let</span> opponentSprite;
            <span class="hljs-keyword">if</span> (scene.isPlayerA) {
                playerSprite = <span class="hljs-string">'cyanCardFront'</span>;
                opponentSprite = <span class="hljs-string">'magentaCardBack'</span>;
            } <span class="hljs-keyword">else</span> {
                playerSprite = <span class="hljs-string">'magentaCardFront'</span>;
                opponentSprite = <span class="hljs-string">'cyanCardBack'</span>;
            };
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) {
                <span class="hljs-keyword">let</span> playerCard = <span class="hljs-keyword">new</span> Card(scene);
                playerCard.render(<span class="hljs-number">475</span> + (i * <span class="hljs-number">100</span>), <span class="hljs-number">650</span>, playerSprite);

                <span class="hljs-keyword">let</span> opponentCard = <span class="hljs-keyword">new</span> Card(scene);
                scene.opponentCards.push(opponentCard.render(<span class="hljs-number">475</span> + (i * <span class="hljs-number">100</span>), <span class="hljs-number">125</span>, opponentSprite).disableInteractive());
            }
        }
    }
}
</code></pre>
<p>With this new class, we're checking whether the client is Player A, and determining what sprites should be used in either case.</p>
<p>Then, we deal cards to our client, while rendering the backs of our opponent's cards at the top the screen and adding them to the opponentCards array that we initialized in our Game scene.</p>
<p>In /src/scenes/game.js, import the Dealer:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Dealer <span class="hljs-keyword">from</span> <span class="hljs-string">'../helpers/dealer'</span>;
</code></pre>
<p>Then replace our dealCards() function with:</p>
<pre><code class="lang-javascript">        <span class="hljs-built_in">this</span>.dealer = <span class="hljs-keyword">new</span> Dealer(<span class="hljs-built_in">this</span>);
</code></pre>
<p>Under code block that begins with "this.socket.on('isPlayerA')", add the following:</p>
<pre><code class="lang-javascript">        <span class="hljs-built_in">this</span>.socket.on(<span class="hljs-string">'dealCards'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            self.dealer.dealCards();
            self.dealText.disableInteractive();
        })
</code></pre>
<p>We also need to update our dealText function to match these changes:</p>
<pre><code class="lang-javascript">        <span class="hljs-built_in">this</span>.dealText.on(<span class="hljs-string">'pointerdown'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            self.socket.emit(<span class="hljs-string">"dealCards"</span>);
        })
</code></pre>
<p>Phew!  We've created a new Dealer class that will handle dealing cards to us and rendering our opponent's cards to the screen.  When the client socket receives the "dealcards" event from the server, it will call the dealCards() function from this new class, and disable the dealText so that we can't just keep generating cards for no reason.</p>
<p>Finally, we've changed the dealText functionality so that when it's pressed, the client emits an event to the server that we want to deal cards, which ties everything together.</p>
<p>Fire up two separate browsers pointed to http://localhost:8080 and hit "DEAL CARDS" on one of them.  You should see different sprites on either screen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Client-1.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Client-2.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Note again that if you're having issues with this step, you may have to close one of your browsers and reload the first one to ensure that both clients have disconnected from the server, which should be logged to your command line console.</p>
<p>We still need to figure out how to render our dropped cards in our opponent's client, and vice-versa.  We can do all of that in our game scene!  Update the code block that begins with "this.input.on('drop')" with one line at the end:</p>
<pre><code class="lang-javascript">        <span class="hljs-built_in">this</span>.input.on(<span class="hljs-string">'drop'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">pointer, gameObject, dropZone</span>) </span>{
            dropZone.data.values.cards++;
            gameObject.x = (dropZone.x - <span class="hljs-number">350</span>) + (dropZone.data.values.cards * <span class="hljs-number">50</span>);
            gameObject.y = dropZone.y;
            gameObject.disableInteractive();
            self.socket.emit(<span class="hljs-string">'cardPlayed'</span>, gameObject, self.isPlayerA);
        })
</code></pre>
<p>When a card is dropped in our client, the socket will emit an event called "cardPlayed", passing the details of the game object and the client's isPlayerA boolean (which could be true or false, depending on whether the client was the first to connect to the server).</p>
<p>Recall that, in our server code, Socket.IO simply receives the "cardPlayed" event and emits the same event back up to all of the clients, passing the same information about the game object and isPlayerA from the client that initiated the event<em>.</em></p>
<p>Let's write what should happen when a client receives a "cardPlayed" event from the server, below the "this.socket.on('dealCards')" code block:</p>
<pre><code class="lang-javascript">         <span class="hljs-built_in">this</span>.socket.on(<span class="hljs-string">'cardPlayed'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">gameObject, isPlayerA</span>) </span>{
            <span class="hljs-keyword">if</span> (isPlayerA !== self.isPlayerA) {
                <span class="hljs-keyword">let</span> sprite = gameObject.textureKey;
                self.opponentCards.shift().destroy();
                self.dropZone.data.values.cards++;
                <span class="hljs-keyword">let</span> card = <span class="hljs-keyword">new</span> Card(self);
                card.render(((self.dropZone.x - <span class="hljs-number">350</span>) + (self.dropZone.data.values.cards * <span class="hljs-number">50</span>)), (self.dropZone.y), sprite).disableInteractive();
            }
        })
</code></pre>
<p>The code block first compares the isPlayerA boolean it receives from the server against the client's own isPlayerA, which is a check to determine whether the client that is receiving the event is the same one that generated it.</p>
<p>Let's think that through a bit further, as it exposes a key component to how our client - server relationship works, using Socket.IO as the connector.</p>
<p>Suppose that Client A connects to the server first, and is told through the "isPlayerA" event that it should change its isPlayerA boolean to <strong>true</strong>.  That's going to determine what kind of cards it generates when a user clicks "DEAL CARDS" through that client.</p>
<p>If Client B connects to the server second, it's never told to alter its isPlayerA boolean, which stays <strong>false</strong>.  That will also determine what kind of cards it generates.</p>
<p>When Client A drops a card, it emits a "cardPlayed" event to the server, passing information about the card that was dropped, and its isPlayerA boolean, which is <strong>true</strong>.  The server then relays all that information back up to all clients with its own "cardPlayed" event.</p>
<p>Client A receives that event from the server, and notes that the isPlayerA boolean from the server is <strong>true</strong>, which means that the event was generated by Client A itself. Nothing special happens.</p>
<p>Client B receives the same event from the server, and notes that the isPlayerA boolean from the server is <strong>true</strong>, although Client B's own isPlayerA is <strong>false</strong>.  Because of this difference, it executes the rest of the code block.  </p>
<p>The ensuing code stores the "texturekey" - basically, the image - of the game object that it receives from the server into a variable called "sprite". It destroys one of the opponent card backs that are rendered at the top of the screen, and increments the "cards" data value in the dropzone so that we can keep placing cards from left to right.  </p>
<p>The code then generates a new card in the dropzone that uses the sprite variable to create the same card that was dropped in the other client (if you had data attached to that game object, you could use a similar approach to attach it here as well).</p>
<p>Your final /src/scenes/game.js code should look like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> io <span class="hljs-keyword">from</span> <span class="hljs-string">'socket.io-client'</span>;
<span class="hljs-keyword">import</span> Card <span class="hljs-keyword">from</span> <span class="hljs-string">'../helpers/card'</span>;
<span class="hljs-keyword">import</span> Dealer <span class="hljs-keyword">from</span> <span class="hljs-string">"../helpers/dealer"</span>;
<span class="hljs-keyword">import</span> Zone <span class="hljs-keyword">from</span> <span class="hljs-string">'../helpers/zone'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Game</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Phaser</span>.<span class="hljs-title">Scene</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">super</span>({
            <span class="hljs-attr">key</span>: <span class="hljs-string">'Game'</span>
        });
    }

    preload() {
        <span class="hljs-built_in">this</span>.load.image(<span class="hljs-string">'cyanCardFront'</span>, <span class="hljs-string">'src/assets/CyanCardFront.png'</span>);
        <span class="hljs-built_in">this</span>.load.image(<span class="hljs-string">'cyanCardBack'</span>, <span class="hljs-string">'src/assets/CyanCardBack.png'</span>);
        <span class="hljs-built_in">this</span>.load.image(<span class="hljs-string">'magentaCardFront'</span>, <span class="hljs-string">'src/assets/magentaCardFront.png'</span>);
        <span class="hljs-built_in">this</span>.load.image(<span class="hljs-string">'magentaCardBack'</span>, <span class="hljs-string">'src/assets/magentaCardBack.png'</span>);
    }

    create() {
        <span class="hljs-built_in">this</span>.isPlayerA = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.opponentCards = [];

        <span class="hljs-built_in">this</span>.zone = <span class="hljs-keyword">new</span> Zone(<span class="hljs-built_in">this</span>);
        <span class="hljs-built_in">this</span>.dropZone = <span class="hljs-built_in">this</span>.zone.renderZone();
        <span class="hljs-built_in">this</span>.outline = <span class="hljs-built_in">this</span>.zone.renderOutline(<span class="hljs-built_in">this</span>.dropZone);

        <span class="hljs-built_in">this</span>.dealer = <span class="hljs-keyword">new</span> Dealer(<span class="hljs-built_in">this</span>);

        <span class="hljs-keyword">let</span> self = <span class="hljs-built_in">this</span>;

        <span class="hljs-built_in">this</span>.socket = io(<span class="hljs-string">'http://localhost:3000'</span>);

        <span class="hljs-built_in">this</span>.socket.on(<span class="hljs-string">'connect'</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">'Connected!'</span>);
        });

        <span class="hljs-built_in">this</span>.socket.on(<span class="hljs-string">'isPlayerA'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            self.isPlayerA = <span class="hljs-literal">true</span>;
        })

        <span class="hljs-built_in">this</span>.socket.on(<span class="hljs-string">'dealCards'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            self.dealer.dealCards();
            self.dealText.disableInteractive();
        })

        <span class="hljs-built_in">this</span>.socket.on(<span class="hljs-string">'cardPlayed'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">gameObject, isPlayerA</span>) </span>{
            <span class="hljs-keyword">if</span> (isPlayerA !== self.isPlayerA) {
                <span class="hljs-keyword">let</span> sprite = gameObject.textureKey;
                self.opponentCards.shift().destroy();
                self.dropZone.data.values.cards++;
                <span class="hljs-keyword">let</span> card = <span class="hljs-keyword">new</span> Card(self);
                card.render(((self.dropZone.x - <span class="hljs-number">350</span>) + (self.dropZone.data.values.cards * <span class="hljs-number">50</span>)), (self.dropZone.y), sprite).disableInteractive();
            }
        })

        <span class="hljs-built_in">this</span>.dealText = <span class="hljs-built_in">this</span>.add.text(<span class="hljs-number">75</span>, <span class="hljs-number">350</span>, [<span class="hljs-string">'DEAL CARDS'</span>]).setFontSize(<span class="hljs-number">18</span>).setFontFamily(<span class="hljs-string">'Trebuchet MS'</span>).setColor(<span class="hljs-string">'#00ffff'</span>).setInteractive();

        <span class="hljs-built_in">this</span>.dealText.on(<span class="hljs-string">'pointerdown'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            self.socket.emit(<span class="hljs-string">"dealCards"</span>);
        })

        <span class="hljs-built_in">this</span>.dealText.on(<span class="hljs-string">'pointerover'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            self.dealText.setColor(<span class="hljs-string">'#ff69b4'</span>);
        })

        <span class="hljs-built_in">this</span>.dealText.on(<span class="hljs-string">'pointerout'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            self.dealText.setColor(<span class="hljs-string">'#00ffff'</span>);
        })

        <span class="hljs-built_in">this</span>.input.on(<span class="hljs-string">'drag'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">pointer, gameObject, dragX, dragY</span>) </span>{
            gameObject.x = dragX;
            gameObject.y = dragY;
        })

        <span class="hljs-built_in">this</span>.input.on(<span class="hljs-string">'dragstart'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">pointer, gameObject</span>) </span>{
            gameObject.setTint(<span class="hljs-number">0xff69b4</span>);
            self.children.bringToTop(gameObject);
        })

        <span class="hljs-built_in">this</span>.input.on(<span class="hljs-string">'dragend'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">pointer, gameObject, dropped</span>) </span>{
            gameObject.setTint();
            <span class="hljs-keyword">if</span> (!dropped) {
                gameObject.x = gameObject.input.dragStartX;
                gameObject.y = gameObject.input.dragStartY;
            }
        })

        <span class="hljs-built_in">this</span>.input.on(<span class="hljs-string">'drop'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">pointer, gameObject, dropZone</span>) </span>{
            dropZone.data.values.cards++;
            gameObject.x = (dropZone.x - <span class="hljs-number">350</span>) + (dropZone.data.values.cards * <span class="hljs-number">50</span>);
            gameObject.y = dropZone.y;
            gameObject.disableInteractive();
            self.socket.emit(<span class="hljs-string">'cardPlayed'</span>, gameObject, self.isPlayerA);
        })
    }

    update() {

    }
}
</code></pre>
<p>Save everything, open two browsers, and hit "DEAL CARDS".  When you drag and drop a card in one client, it should appear in the dropzone of the other, while also deleting a card back, signifying that a card has been played:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Card-Played-1.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Card-Played-2.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>That's it!  You should now have a functional template for your multiplayer card game, which you can use to add your own cards, art, and game logic.</p>
<p>One first step could be to add to your Dealer class by making it shuffle an array of cards and return a random one (hint: check out <a target="_blank" href="https://photonstorm.github.io/phaser3-docs/Phaser.Math.RandomDataGenerator.html#shuffle__anchor">Phaser.Math.RND.shuffle([array])</a>).</p>
<p>Happy coding!</p>
<p>If you enjoyed this article, please consider <a target="_blank" href="https://www.nightpathpub.com/">checking out my games and books</a>, <a target="_blank" href="https://www.youtube.com/msfarzan?sub_confirmation=1">subscribing to my YouTube channel</a>, or <a target="_blank" href="https://discord.gg/RF6k3nB">joining the <em>Entromancy</em> Discord</a>.</p>
<p>M. S. Farzan, Ph.D. has written and worked for high-profile video game companies and editorial websites such as Electronic Arts, Perfect World Entertainment, Modus Games, and MMORPG.com, and has served as the Community Manager for games like <em>Dungeons &amp; Dragons Neverwinter</em> and <em>Mass Effect: Andromeda</em>. He is the Creative Director and Lead Game Designer of <em><a target="_blank" href="https://www.nightpathpub.com/rpg">Entromancy: A Cyberpunk Fantasy RPG</a></em> and author of <em><a target="_blank" href="http://nightpathpub.com/books">The Nightpath Trilogy</a></em>. Find M. S. Farzan on Twitter <a target="_blank" href="https://twitter.com/sominator">@sominator</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to implement server-side rendering in your React app in three simple steps ]]>
                </title>
                <description>
                    <![CDATA[ By Rohit Kumar Here’s what we will build in this tutorial: a nice React card like this one. In this tutorial, we’ll use server-side rendering to deliver an HTML response when a user or crawler hits a page URL. We’ll handle the latter requests on the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/server-side-rendering-your-react-app-in-three-simple-steps-7a82b95db82e/</link>
                <guid isPermaLink="false">66c35e94c7095d76345eaff8</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ progressive web app ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 29 Feb 2020 11:41:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9c5d740569d1a4ca31bc.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><img src="https://www.freecodecamp.org/news/content/images/2020/03/1_wk04sWGQkw36_XLFvPACrA-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>By Rohit Kumar</p>
<p>Here’s what we will build in this tutorial: a nice React card like this one.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/1_wk04sWGQkw36_XLFvPACrA-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In this tutorial, we’ll use server-side rendering to deliver an HTML response when a user or crawler hits a page URL. We’ll handle the latter requests on the client side.</p>
<p>Why do we need it?</p>
<p>Let me guide you to the answer.</p>
<h2 id="heading-whats-the-difference-between-client-side-rendering-and-server-side-rendering">What’s the difference between client-side rendering and server-side rendering?</h2>
<p>In <strong>Client-side rendering,</strong> your browser downloads a minimal HTML page. It renders the JavaScript and fills the content into it.</p>
<p><strong>Server-side rendering,</strong> on the other hand, renders the React components on the server. The output is HTML content.</p>
<p>You can combine these two to create an isomorphic app.</p>
<h2 id="heading-cons-of-rendering-react-on-the-server">Cons of Rendering React on the Server</h2>
<ul>
<li>SSR can improve performance if your application is small. But it can also degrade performance if it is heavy.</li>
<li>It increases response time (and it can be worse if the server is busy).</li>
<li>It increases response size, which means the page takes longer to load.</li>
<li>It increases the complexity of the application.</li>
</ul>
<h2 id="heading-when-should-you-use-server-side-rendering">When should you use Server Side Rendering?</h2>
<p>Despite these consequences of SSR, there are some situations in which you can and should use it.</p>
<h3 id="heading-1-seo">1. SEO</h3>
<p>Every website wants to appear in searches. Correct me if I’m wrong.</p>
<p>Unfortunately, Search engine crawlers do not yet understand/render JavaScript.</p>
<p>This means they see a blank page, no matter how helpful your site is.</p>
<p>Many folks say that Google’s crawler <a target="_blank" href="https://www.searchenginejournal.com/googles-search-crawlers-natively-render-javascript-based-pages/226313/">now renders JavaScript</a>.</p>
<p>To test this, I deployed the app on Heroku. Here is what I saw on the Google Search Console:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*KgOtUd6XBbeZvR1FDBGcXA.png" alt="Image" width="800" height="537" loading="lazy">
<em>Google’s crawler does not render React</em></p>
<p>A blank page.</p>
<p>This was the biggest reason I explored server-side rendering. Especially when it is a <a target="_blank" href="https://yoast.com/what-is-cornerstone-content/">cornerstone page</a> such as a landing page, blog, and so on.</p>
<p>To verify if Google renders your site, visit:</p>
<p>Search Console Dashboard &gt; Crawl &gt; Fetch as Google. Enter the page URL or leave it empty for the homepage.</p>
<p>Select FETCH AND RENDER. Once complete, click to see the result.</p>
<h3 id="heading-2-improve-performance">2. Improve performance</h3>
<p>In SSR, the application performance depends on the server’s resources and user’s network speed. This makes it very useful for content-heavy sites.</p>
<p><em>For Example</em>, say that you have a medium-price mobile phone with slow internet speed. You try to access a site that downloads 4MB of data before you can see anything.</p>
<p>Would you be able to see anything on your screen within 2–4 seconds?</p>
<p>Would you visit that site again?</p>
<p>I don’t think you would.</p>
<p>Another major improvement is in <a target="_blank" href="https://developers.google.com/web/tools/lighthouse/audits/time-to-interactive">First User Interaction Time</a>. This is the difference in time from when a user hits the URL to when they see content.</p>
<p>Here’s the comparison. I tested it on a development Mac.</p>
<h4 id="heading-react-rendered-on-server">React Rendered on Server</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*kYMHoa7OemCHA_KBzJ1w-w.png" alt="Image" width="800" height="347" loading="lazy">
<em>SSR performance report (Chrome)</em></p>
<p>The first interaction time is 300ms. Hydrate finishes at 400ms. The load event exits at 500ms approximately. You can see this by checking out the image above.</p>
<h4 id="heading-react-rendered-on-clients-browser">React Rendered on Client’s Browser</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*wquRCRboPDi7Ix2HAxvCAA.png" alt="Image" width="800" height="342" loading="lazy">
<em>Client side performance report (Chrome)</em></p>
<p>The first interaction time is 400ms. The load event exits at 470ms.</p>
<p>The result speaks for itself. There’s a 100ms difference in the First User Interaction Time for such a small app.</p>
<h3 id="heading-how-does-it-work-4-simple-steps">How does it Work? — (4 Simple Steps)</h3>
<ul>
<li>Create a fresh Redux Store on every request.</li>
<li>Optionally dispatch some actions.</li>
<li>Get the state out of the Store and perform SSR.</li>
<li>Send the state obtained in the previous step along with the response.</li>
</ul>
<p>We will use the state passed in the response for creating the initial state on client-side.</p>
<p>Before you get started, <a target="_blank" href="https://github.com/Rohitkrops/ssr">clone/download the complete example from Github</a> and use it for reference.</p>
<h3 id="heading-getting-started-by-setting-up-our-app">Getting Started by Setting up our App</h3>
<p>First, open your favourite editor and shell. Create a new folder for your application. Let’s start.</p>
<pre><code class="lang-bash">npm init --yes
</code></pre>
<p>Fill in the details. After <code>package.json</code> is created, copy the dependencies and scripts below into it.</p>
<p>Install all dependencies by running:</p>
<pre><code class="lang-bash">npm install
</code></pre>
<p>You need to configure Babel and webpack for our build script to work.</p>
<p>Babel transforms ESM and react into Node and browser-understood code.</p>
<p>Create a new file <code>.babelrc</code> and put the line below in it.</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"presets"</span>: [<span class="hljs-string">"@babel/env"</span>, <span class="hljs-string">"@babel/react"</span>]
}
</code></pre>
<p>webpack bundles our app and its dependencies into a single file. Create another file <code>webpack.config.js</code> with the following code in it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);<span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-attr">entry</span>: {
        <span class="hljs-attr">client</span>: <span class="hljs-string">'./src/client.js'</span>,
        <span class="hljs-attr">bundle</span>: <span class="hljs-string">'./src/bundle.js'</span>
    },
    <span class="hljs-attr">output</span>: {
        <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">'assets'</span>),
        <span class="hljs-attr">filename</span>: <span class="hljs-string">"[name].js"</span>
    },
    <span class="hljs-attr">module</span>: {
        <span class="hljs-attr">rules</span>: [
            { <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.js$/</span>, exclude: <span class="hljs-regexp">/node_modules/</span>, loader: <span class="hljs-string">"babel-loader"</span> }
        ]
    }
}
</code></pre>
<p>The build process output’s two files:</p>
<ol>
<li><code>assets/bundle.js</code> — pure client side app.</li>
<li><code>assets/client.js</code> — client side companion for SSR.</li>
</ol>
<p>The <code>src/</code> folder contains the source code. The Babel compiled files go into <code>views/</code>. <code>views</code> directory will be created automatically if not present.</p>
<h3 id="heading-why-do-we-need-to-compile-source-files">Why do we need to compile source files?</h3>
<p>The reason is the syntax <a target="_blank" href="http://jsmodules.io/cjs.html">difference between ESM &amp; CommonJS</a>. While writing React and Redux, we heavily use import and export in all files.</p>
<p>Unfortunately, they don’t work in Node. Here comes Babel to rescue. The script below tells Babel to compile all files in the <code>src</code> directory and put the result in <code>views.</code></p>
<pre><code class="lang-json"><span class="hljs-string">"babel"</span>: <span class="hljs-string">"babel src -d views"</span>,
</code></pre>
<p>Now, Node can run them.</p>
<h3 id="heading-copy-precoded-amp-static-files">Copy Precoded &amp; Static files</h3>
<p>If you have already cloned the repository, copy from it. Otherwise d<a target="_blank" href="https://www.dropbox.com/s/2iijlivmlye6pqp/ssr-static.zip?dl=0">ownload ssr-static.zip file from Dropbox</a>. Extract it and keep these three folders inside your app directory. Here’s what they contain.</p>
<ol>
<li>React <code>App</code> and components resides in <code>src/components</code>.</li>
<li>Redux files in <code>src/redux/</code>.</li>
<li><code>assets/ &amp; media/</code>: Contain static files such as <code>style.css</code> and images.</li>
</ol>
<h3 id="heading-server-side">Server Side</h3>
<p>Create two new files named <code>server.js</code> and <code>template.js</code> inside the <code>src/</code> folder.</p>
<h3 id="heading-1-srcserverjs">1. src/server.js</h3>
<p>Magic happens here. This is the code you’ve been searching for.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { renderToString } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/server'</span>;
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;
<span class="hljs-keyword">import</span> configureStore <span class="hljs-keyword">from</span> <span class="hljs-string">'./redux/configureStore'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/app'</span>;

<span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">render</span>(<span class="hljs-params">initialState</span>) </span>{
  <span class="hljs-comment">// Model the initial state  </span>
  <span class="hljs-keyword">const</span> store = configureStore(initialState);
  <span class="hljs-keyword">let</span> content = renderToString(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span> &gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>);
  <span class="hljs-keyword">const</span> preloadedState = store.getState();
  <span class="hljs-keyword">return</span> {
    content,
    preloadedState
  };
};
</code></pre>
<p>Instead of rendering our app, we need to wrap it into a function and export it. The function accepts the initial state of the application.</p>
<p>Here’s how it works.</p>
<ol>
<li>Pass <code>initialState</code> to <code>configureStore()</code>. <code>configureStore()</code>returns a new Store instance. Hold it inside the <code>store</code> variable.</li>
<li>Call <code>renderToString()</code> method, providing our App as input. It renders our app on the server and returns the HTML produced. Now, the variable <code>content</code> stores the HTML.</li>
<li>Get the state out of Redux Store by calling <code>getState()</code> on <code>store</code>. Keep it in a variable <code>preloadedState</code>.</li>
<li>Return the <code>content</code> and <code>preloadedState</code>. We will pass these to our template to get the final HTML page.</li>
</ol>
<h4 id="heading-2-srctemplatejs"><code>2. src/template.js</code></h4>
<p><code>template.js</code> exports a function. It takes <code>title</code>, <code>state</code> and <code>content</code> as input. It injects them into the template and returns the final HTML document.</p>
<p>To pass along the state, the template attaches <code>state</code> to <code>window.__STATE__</code> inside a <code>&lt;scri</code>pt&gt; tag.</p>
<p>Now you can read <code>state</code> on the client side by accessing <code>window.__STATE__</code>.</p>
<p>We also include the SSR companion <code>assets/client.js</code> client-side application in another script tag.</p>
<p>If you request the pure client version, it only puts <code>assets/bundle.js</code> inside the script tag.</p>
<h3 id="heading-the-client-side">The Client Side</h3>
<p>The client side is pretty straightforward.</p>
<h3 id="heading-1-srcbundlejs">1. src/bundle.js</h3>
<p>This is how you write the React and Redux <code>Provider</code> wrap. It is our pure client-side app. No tricks here.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { render } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;
<span class="hljs-keyword">import</span> configureStore <span class="hljs-keyword">from</span> <span class="hljs-string">'./redux/configureStore'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/app'</span>;

<span class="hljs-keyword">const</span> store = configureStore();
render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span> &gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>,
  <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#app'</span>)
);
</code></pre>
<h3 id="heading-2-srcclientjs">2. src/client.js</h3>
<p>Looks familiar? Yeah, there is nothing special except <code>window.__STATE__.</code> All we need to do is grab the initial state from <code>window.__STATE__</code> and pass it to our <code>configureStore()</code> function as the initial state.</p>
<p>Let’s take a look at our new client file:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { hydrate } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;
<span class="hljs-keyword">import</span> configureStore <span class="hljs-keyword">from</span> <span class="hljs-string">'./redux/configureStore'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/app'</span>;

<span class="hljs-keyword">const</span> state = <span class="hljs-built_in">window</span>.__STATE__;
<span class="hljs-keyword">delete</span> <span class="hljs-built_in">window</span>.__STATE__;
<span class="hljs-keyword">const</span> store = configureStore(state);
hydrate(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span> &gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>,
  <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#app'</span>)
);
</code></pre>
<p>Let’s review the changes:</p>
<ol>
<li>Replace <code>render()</code> with <code>hydrate()</code>. <code>[hydrate()](https://reactjs.org/docs/react-dom.html#hydrate)</code> is the same as <code>render()</code> but is used to hydrate elements rendered by <code>[ReactDOMServer](https://reactjs.org/docs/react-dom-server.html)</code>. It ensures that the content is the same on the server and the client.</li>
<li>Read the state from the global window object <code>window.__STATE__</code>. Store it in a variable and delete the <code>window.__STATE__</code>.</li>
<li>Create a fresh store with <code>state</code> as initialState.</li>
</ol>
<p>All done here.</p>
<h2 id="heading-putting-it-all-together">Putting it all together</h2>
<h3 id="heading-indexjs">Index.js</h3>
<p>This is the entry point of our application. It handles requests and templating.</p>
<p>It also declares an <code>initialState</code> variable. I have modelled it with data in the <code>assets/data.json</code> file. We will pass it to our <code>ssr()</code> function.</p>
<p><em>Note: While referencing a file that is inside <code>src/</code> from a file outside <code>src/</code> , use normal <code>require()</code> and replace <code>src/</code> by <code>views/</code>. You know the reason (Babel compile).</em></p>
<p>Routing</p>
<ol>
<li><code>/</code>: By default server-rendered homepage.</li>
<li><code>/client</code>: Pure client-side rendering example.</li>
<li><code>/exit</code>: Server stop button. Only available in development.</li>
</ol>
<h4 id="heading-build-amp-run">Build &amp; Run</h4>
<p>It’s time to build and run our application. We can do this with a single line of code.</p>
<pre><code class="lang-bash">npm run build &amp;&amp; npm run start
</code></pre>
<p>Now, the application is running at <a target="_blank" href="http://localhost:3000/">http://localhost:3000</a>.</p>
<h3 id="heading-ready-to-become-a-react-pro">Ready to become a React Pro?</h3>
<p>I am starting a new series from next Monday to get your React skills blazing, immediately.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*TEecv1nLg253xmyGgddhOw.gif" alt="Image" width="500" height="226" loading="lazy">
<em>subscription link below ?</em></p>
<h3 id="heading-thank-you-for-reading-this">Thank you for reading this.</h3>
<p>If you like it and find it useful, follow me on <a target="_blank" href="http://twitter.com/rohitkrops">Twitter</a> &amp; <a target="_blank" href="http://bit.ly/2zVj1fX">Webflow</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use GitHub and ES6 Features to Create and Structure Your Code ]]>
                </title>
                <description>
                    <![CDATA[ By M. S. Farzan If you're moving from coding tutorials into creating your own JavaScript projects, you'll want to become familiar with using a version control system like GitHub and benefiting from ES6 features to clean up your code and streamline yo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-github-and-es6-features-to-create-and-structure-your-code/</link>
                <guid isPermaLink="false">66d851f32c0761b6f5a251f3</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GitHub ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Integrated Development Environment   ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learn to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tutorial purgatory ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 19 Dec 2019 17:00:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9e9b740569d1a4ca3e11.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By M. S. Farzan</p>
<p>If you're moving from coding tutorials into creating your own JavaScript projects, you'll want to become familiar with using a version control system like <a target="_blank" href="https://github.com/">GitHub</a> and benefiting from <a target="_blank" href="https://www.w3schools.com/js/js_es6.asp">ES6 features</a> to clean up your code and streamline your development process.</p>
<p>In this new video, we'll walk through cloning an existing repository from GitHub, creating your own local and remote repositories, utilizing node package manager (NPM) to install dependencies, creating a streamlined code base using ES6 classes, import/export modules, and arrow functions, and adding, committing, and pushing changes to GitHub.</p>
<p>Plus, we'll talk through the basic file structure for a <a target="_blank" href="https://phaser.io/">Phaser 3</a> project!</p>
<p>Check it out (50 minute watch):</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/z9xz-R4iuaU" 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>Happy coding!</p>
<p>If you enjoyed this article, please consider <a target="_blank" href="https://www.nightpathpub.com/">checking out my games and books</a>, <a target="_blank" href="https://www.youtube.com/msfarzan?sub_confirmation=1">subscribing to my YouTube channel</a>, or <a target="_blank" href="https://discord.gg/RF6k3nB">joining the <em>Entromancy</em> Discord</a>.</p>
<p>M. S. Farzan, Ph.D. has written and worked for high-profile video game companies and editorial websites such as Electronic Arts, Perfect World Entertainment, Modus Games, and MMORPG.com, and has served as the Community Manager for games like <em>Dungeons &amp; Dragons Neverwinter</em> and <em>Mass Effect: Andromeda</em>. He is the Creative Director and Lead Game Designer of <em><a target="_blank" href="https://www.nightpathpub.com/rpg">Entromancy: A Cyberpunk Fantasy RPG</a></em> and author of <em><a target="_blank" href="http://nightpathpub.com/books">The Nightpath Trilogy</a></em>. Find M. S. Farzan on Twitter <a target="_blank" href="https://twitter.com/sominator">@sominator</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Node.js Development with modern JavaScript using FortJs ]]>
                </title>
                <description>
                    <![CDATA[ By Ujjwal Gupta Introduction Nodejs gives you the power to write server side code using JavaScript. In fact, it is very easy and fast to create a web server using Nodejs. There are several frameworks available on Node package manager which makes the ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/nodejs-development-with-modern-javascript-using-fortjs/</link>
                <guid isPermaLink="false">66d461728812486a37369d6c</guid>
                
                    <category>
                        <![CDATA[ dependency injection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 23 Oct 2019 02:37:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-20-36-31-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ujjwal Gupta</p>
<h2 id="heading-introduction">Introduction</h2>
<p>Nodejs gives you the power to write server side code using JavaScript. In fact, it is very easy and fast to create a web server using Nodejs. There are several frameworks available on Node package manager which makes the development even easier and faster.</p>
<p>But there are a few challenges in Nodejs development:</p>
<ul>
<li>Nodejs is all about callbacks, and with more and more callbacks you end up with a situation called callback hell.</li>
<li>Writing readable code.</li>
<li>Writing maintainable code.</li>
<li>You don't get much intellisense support which makes development slow.</li>
</ul>
<p>If you are quite experienced and have a good knowledge of Nodejs, you can use different techniques and try to minimize these challenges.</p>
<p>The best way to solve these problems is by using modern JavaScript ES6, ES7 or TypeScript, whatever you feel comfortable with. I recommend TypeScript, because it provides intillisense support for every word of code which makes your development faster.</p>
<p>So I created a framework called <a target="_blank" href="http://fortjs.info/">FortJs</a> which is very easy to learn and use. FortJs enables you to write server-side code using ES6 or TypeScript which is modular, secure, and pretty much just beautiful and readable.</p>
<h2 id="heading-features">Features</h2>
<p>Some of the important features of FortJs are:  </p>
<ul>
<li>Based on <a target="_blank" href="https://github.com/ujjwalguptaofficial/fort">Fort</a> architecture. </li>
<li>MVC Framework and follows OOPS approach so everything is class and object.</li>
<li>Provides components - Wall, Shield and Guard. Components help modularize the application.</li>
<li>Uses ES6 async/await or promise for executing asychronous code.</li>
<li>Everything is configurable - you can configure your session store, view engine, websocket etc.</li>
<li>Dependency Injection.</li>
<li>Everything can be unit tested, so you can use a <a target="_blank" href="https://guide.freecodecamp.org/agile/test-driven-development/">TDD</a> approach.</li>
</ul>
<h2 id="heading-lets-code">Let's Code</h2>
<p>In this article I am going to create a REST API using FortJs and ES6. But you can use the same code and steps to implement using TypeScript too.</p>
<h3 id="heading-project-setup">Project Setup</h3>
<p>FortJs provides a CLI - fort-creator. This helps you set up the project and develop faster. Let's use the CLI to develop.</p>
<p> Perform the below steps sequentially:</p>
<ul>
<li>Open your terminal or command prompt.</li>
<li>Install <strong>fort-creator</strong> globally - run the command "npm i fort-creator -g". Note: Make sure you have Nodejs installed in your system.</li>
<li>Create a new project - run the command "fort-creator new my-app". Here “my-app” is the name of the app, so you can choose any name. The CLI will prompt you to choose the language with two options: TypeScript and JavaScript. Choose your language by using the arrow keys and press enter - i have chosen JavaScript. It will take some time to create the project, so please wait until you see "new project my-app created".</li>
<li>Enter into the project directory - "cd my-app".<br>Start the development server with live reloading - run the command "fort-creator start".</li>
<li>Open the browser and type the URL - <a target="_blank" href="http://localhost:4000/">http://localhost:4000/</a>.  </li>
</ul>
<p>You should see something like this in the browser.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-20-36-31.png" alt="Image" width="600" height="400" loading="lazy">
<em>FortJs starter page</em></p>
<p>Let's understand how this page is rendered:</p>
<ul>
<li>Open the project folder in your favourite code editor. I am going to use VS Code. You will see many folders inside project root such as controllers, views, etc. Every folder is grouped by their use - for example, the controllers folder contains all controllers and the views folder contains all views.</li>
<li>Open the controllers folder -&gt; Inside the controllers, you will see a file name - default_controller. Let's open it and observe the code. The file contains a class DefaultController - this is a <a target="_blank" href="http://fortjs.info/tutorial/controller/">controller</a> class and it contains methods which return some http response.</li>
<li>Inside the class DefaultController, you will see a method 'index' - this is the one which is rendering current output to the browser. The method is known as <a target="_blank" href="http://fortjs.info/tutorial/worker/">worker</a> in FortJs because they do some kind of work and return the result as an http response. Let's observe the index method code:  </li>
</ul>
<pre><code><span class="hljs-keyword">const</span> data = {  
    <span class="hljs-attr">title</span>: title  
}  
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> viewResult(<span class="hljs-string">'default/index.html'</span>, data);  
<span class="hljs-keyword">return</span> result;
</code></pre><p>It creates a data object and passes that object into the <strong>viewResult</strong> method. The <strong>viewResult</strong> method takes two parameters - the view location and view data. The work of <strong>viewResult</strong> is to render the view and return a response, which we are seeing in the browser.</p>
<ul>
<li>Let's find the view code and understand it. Open the views folder - &gt; open default folder - &gt; open index.html. This is our view code. It is simple HTML code along with some mustache syntax. The default view engine for Fortjs is mustache.</li>
</ul>
<p>I hope you have understood the project architecture. If you are having any difficulties or doubts, please feel free to ask in the comments section.</p>
<p>Now we will move to next part of this article where we will learn how to create a simple rest API.</p>
<h2 id="heading-rest">REST</h2>
<p>We are going to create a REST endpoint for entity user - which will perform CRUD operations for the user such as adding a user, deleting a user, getting a user, and updating a user.</p>
<p>According to REST:</p>
<ol>
<li>Adding user - should be done using the http method "<code>POST</code>"</li>
<li>Deleting user - should be done using the http method "<code>REMOVE</code>"</li>
<li>Getting user - should be done using the http method "<code>GET</code>"</li>
<li>Updating user - should be done using the http method "<code>PUT</code>"</li>
</ol>
<p>For creating an endpoint, we need to create a Controller similar to the default controller explained earlier.</p>
<p>Execute the command  "<code>fort-creator add</code>". It will ask you to "Choose the component to add ?" Choose Controller &amp; press <strong>enter</strong>. Enter the controller name "User" and press <strong>enter</strong>.</p>
<p>Now that we have created the user controller we need to inform FortJs by adding it to routes. The route is used to map our controller to a path.</p>
<p>Since our entity is user, "<code>/user</code>" will be a good route. Let's add it. Open routes.js inside the root directory of the project and add <code>UserController</code> to routes.</p>
<p>After adding UserController, routes.js will look like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { DefaultController } <span class="hljs-keyword">from</span> <span class="hljs-string">"./controllers/default_controller"</span>;
<span class="hljs-keyword">import</span> { UserController } <span class="hljs-keyword">from</span> <span class="hljs-string">"./controllers/user_controller"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> routes = [{
    <span class="hljs-attr">path</span>: <span class="hljs-string">"/*"</span>,
    <span class="hljs-attr">controller</span>: DefaultController
},
{
    <span class="hljs-attr">path</span>: <span class="hljs-string">"/user"</span>,
    <span class="hljs-attr">controller</span>: UserController
}]
</code></pre>
<p>So when an http request has the path "/user" then UserController will be called. </p>
<p>Let's open the url - <a target="_blank" href="http://localhost:4000/user">http://localhost:4000/user</a>.</p>
<p>Note: If you have stopped FortJs while adding the controller, please start it again by running the cmd - <code>fort-creator start</code></p>
<p>And you see a white page right?</p>
<p>This is because we are not returning anything from the index method and thus we get a blank response. Let's return a text "Hello World" from the index method. Add the below code inside the index method and save:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> textResult(<span class="hljs-string">'Hello World'</span>);
</code></pre>
<p>Refresh the url - <a target="_blank" href="http://localhost:4000/user">http://localhost:4000/user</a></p>
<p>And you see "Hello World" right?</p>
<p>Now, let's convert "UserController" to a REST API. But before writing code for the REST API, let's create a dummy service which will do CRUD operations for users.</p>
<h3 id="heading-service">Service</h3>
<p>Create a folder called “services” and then a file “user_service.js” inside the folder. Paste the below code inside the file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> store = {
    <span class="hljs-attr">users</span>: [{
        <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
        <span class="hljs-attr">name</span>: <span class="hljs-string">"ujjwal"</span>,
        <span class="hljs-attr">address</span>: <span class="hljs-string">"Bangalore India"</span>,
        <span class="hljs-attr">emailId</span>: <span class="hljs-string">"ujjwal@mg.com"</span>,
        <span class="hljs-attr">gender</span>: <span class="hljs-string">"male"</span>,
        <span class="hljs-attr">password</span>: <span class="hljs-string">"admin"</span>
    }]
}

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserService</span> </span>{
    getUsers() {
        <span class="hljs-keyword">return</span> store.users;
    }

    addUser(user) {
        <span class="hljs-keyword">const</span> lastUser = store.users[store.users.length - <span class="hljs-number">1</span>];
        user.id = lastUser == <span class="hljs-literal">null</span> ? <span class="hljs-number">1</span> : lastUser.id + <span class="hljs-number">1</span>;
        store.users.push(user);
        <span class="hljs-keyword">return</span> user;
    }

    updateUser(user) {
        <span class="hljs-keyword">const</span> existingUser = store.users.find(<span class="hljs-function"><span class="hljs-params">qry</span> =&gt;</span> qry.id === user.id);
        <span class="hljs-keyword">if</span> (existingUser != <span class="hljs-literal">null</span>) {
            existingUser.name = user.name;
            existingUser.address = user.address;
            existingUser.gender = user.gender;
            existingUser.emailId = user.emailId;
            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        }
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }

    getUser(id) {
        <span class="hljs-keyword">return</span> store.users.find(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.id === id);
    }

    removeUser(id) {
        <span class="hljs-keyword">const</span> index = store.users.findIndex(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.id === id);
        store.users.splice(index, <span class="hljs-number">1</span>);
    }
}
</code></pre>
<p>The above code contains a variable store which contains a collection of users. The method inside the service does operations like add, update, delete, and get on that store.</p>
<p>We will use this service in REST API implementation.</p>
<h3 id="heading-get">GET</h3>
<p>For the route "/user" with the http method "GET", the API should return a list of all users. </p>
<p>In order to implement this, let's rename the "index" method inside user_controller.js to "getUsers" making it semantically correct. Then paste the below code inside the method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> service = <span class="hljs-keyword">new</span> UserService();
<span class="hljs-keyword">return</span> jsonResult(service.getUsers());
</code></pre>
<p>Now user_controller.js looks like this:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { Controller, DefaultWorker, Worker, textResult, jsonResult } <span class="hljs-keyword">from</span> <span class="hljs-string">"fortjs"</span>;
<span class="hljs-keyword">import</span> { UserService } <span class="hljs-keyword">from</span> <span class="hljs-string">"../services/user_service"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{

    @DefaultWorker()
    <span class="hljs-keyword">async</span> getUsers() {
        <span class="hljs-keyword">const</span> service = <span class="hljs-keyword">new</span> UserService();
        <span class="hljs-keyword">return</span> jsonResult(service.getUsers());
    }
}
</code></pre>
<p>Here, we are using the decorator DefaultWorker. The DefaultWorker does two things: it adds the route "/" &amp; the http method "GET". It's a shortcut for this scenario. In the next part, we will use other decorators to customize the route.</p>
<p>Let's test this by calling the url <a target="_blank" href="http://localhost:4000/user">http://localhost:4000/user</a>. You can open this in the browser or use any http client tools like postman or curl. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-21-53-59.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Ok, so we have successfully created an end point :) .</p>
<p>Let's look again at our code and see if we can make it better: </p>
<ol>
<li>The service "UserService" is tightly coupled with Controller "UserController" which becomes a problem for unit testing "UserController". So we will use <a target="_blank" href="http://fortjs.info/tutorial/dependency-injection/">dependency injection</a> by FortJs to inject UserService.</li>
<li>We are creating an instance of "UserService" every time the method getUsers is called. But what we need from "UserService" is a single object and then call the "UserService" method from the object. </li>
</ol>
<p>So if we can somehow store an object of "UserService" then we can make our code faster (because calling new does some work under the hood). For this we will use the singleton feature of FortJs.</p>
<p>Let's change the user_controller.js code by the below code: </p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { Controller, DefaultWorker, Worker, textResult, jsonResult, Singleton } <span class="hljs-keyword">from</span> <span class="hljs-string">"fortjs"</span>;
<span class="hljs-keyword">import</span> { UserService } <span class="hljs-keyword">from</span> <span class="hljs-string">"../services/user_service"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{

    @DefaultWorker()
    <span class="hljs-keyword">async</span> getUsers(@Singleton(UserService) service) {
        <span class="hljs-keyword">return</span> jsonResult(service.getUsers());
    }
}
</code></pre>
<p>As you can see, the only change is that we are using the "Singleton" decorator in the method getUsers. This will create a singleton and inject that singleton when getUsers is called. This singleton will be available throughout the application.</p>
<p>Since service is now a parameter, we can manually pass the parameter while calling. This makes getUsers unit testable.</p>
<p>For doing unit testing or E2E testing, please read this test doc - <a target="_blank" href="http://fortjs.info/tutorial/test/">http://fortjs.info/tutorial/test/</a></p>
<h3 id="heading-post">POST</h3>
<p>Let's add a method "addUser" which will extract data from the request body and call service to add a user.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
        <span class="hljs-keyword">const</span> user = {
            <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
            <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
            <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
            <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
            <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
        };
        <span class="hljs-keyword">const</span> newUser = service.addUser(user);
        <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre>
<blockquote>
<p>In the above code we are creating the Singleton of the UserService again. So the question is will it create another object?</p>
</blockquote>
<p>No it will be same object that was in getUser. FortJs supplies the object as a parameter when it calls the method.</p>
<p>The methods created are by default not visible for an http request. So in order to make this method visible for the http request, we need to mark this as a worker. </p>
<p>A method is marked as a worker by adding the decorator "Worker". The Worker decorator takes a list of http methods and makes that method available for only those http methods. So let's add the decorator:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Post])
<span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> user = {
        <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
        <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
        <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
        <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
        <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
    };
    <span class="hljs-keyword">const</span> newUser = service.addUser(user);
    <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre>
<p>Now the route of this method is the same as the name of the method that is "addUser". You can check this by sending a post request to <a target="_blank" href="http://localhost:4000/user/addUser">http://localhost:4000/user/addUser</a> with user data in the body.</p>
<p>But we want the route to be "/", so that it will be a rest API. The route of the worker is configured by using the decorator "Route". Let's change the route now.</p>
<pre><code>@Worker([HTTP_METHOD.Post])
@Route(<span class="hljs-string">"/"</span>)
<span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> user = {
        <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
        <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
        <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
        <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
        <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
    };
    <span class="hljs-keyword">const</span> newUser = service.addUser(user);
    <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre><p>Now our end point is configured for a post request. Let's test this by sending a post request to <a target="_blank" href="http://localhost:4000/user/">http://localhost:4000/user/</a> with user data in the body.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-22-43-19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>It returns the user created with id which is our logic. So we have created the end point for the post request, but one important thing to do is to validate the data. Validation is an essential part of any app and is very important for a backend application.</p>
<p>So far, our code is clean and readable. But if we add validation code it will become a little dirty. </p>
<p>Worry not, FortJs provides the component <a target="_blank" href="http://fortjs.info/tutorial/guard/">Guard</a> for this kind of work. A/c to the FortJs docs:</p>
<blockquote>
<p>Guard is security layer on top of Worker. It controls whether a request should be allowed to call the Worker.</p>
</blockquote>
<p>So we are going to use guard for validation of the data. Let's create the guard using fort-creator. Execute the command  <code>fort-creator add</code> and choose Guard. Enter the file name "UserValidator". There will be a file "user_validator_guard.js" created inside the guards folder. Open that file.</p>
<p>A guard has access to the body, so you can validate the data inside that. Returning null inside the method <code>check</code> means that we're allowing to call the worker. Returning anything else means block the call.</p>
<p>Let's make it clearer by writing code for the validation. Paste the below code inside the file "user_validator_guard.js":</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { Guard, textResult, HTTP_STATUS_CODE } <span class="hljs-keyword">from</span> <span class="hljs-string">"fortjs"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserValidatorGuard</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Guard</span> </span>{

    <span class="hljs-keyword">async</span> check() {
        <span class="hljs-keyword">const</span> user = {
            <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
            <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
            <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
            <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
            <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
        };
        <span class="hljs-keyword">const</span> errMsg = <span class="hljs-built_in">this</span>.validate(user);
        <span class="hljs-keyword">if</span> (errMsg == <span class="hljs-literal">null</span>) {
            <span class="hljs-comment">// pass user to worker method, so that they dont need to parse again  </span>
            <span class="hljs-built_in">this</span>.data.user = user;
            <span class="hljs-comment">// returning null means - guard allows request to pass  </span>
            <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">return</span> textResult(errMsg, HTTP_STATUS_CODE.BadRequest);
        }
    }

    validate(user) {
        <span class="hljs-keyword">let</span> errMessage;
        <span class="hljs-keyword">if</span> (user.name == <span class="hljs-literal">null</span> || user.name.length &lt; <span class="hljs-number">5</span>) {
            errMessage = <span class="hljs-string">"name should be minimum 5 characters"</span>
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.password == <span class="hljs-literal">null</span> || user.password.length &lt; <span class="hljs-number">5</span>) {
            errMessage = <span class="hljs-string">"password should be minimum 5 characters"</span>;
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.gender == <span class="hljs-literal">null</span> || [<span class="hljs-string">"male"</span>, <span class="hljs-string">"female"</span>].indexOf(user.gender) &lt; <span class="hljs-number">0</span>) {
            errMessage = <span class="hljs-string">"gender should be either male or female"</span>;
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.emailId == <span class="hljs-literal">null</span> || !<span class="hljs-built_in">this</span>.isValidEmail(user.emailId)) {
            errMessage = <span class="hljs-string">"email not valid"</span>;
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.address == <span class="hljs-literal">null</span> || user.address.length &lt; <span class="hljs-number">10</span>) {
            errMessage = <span class="hljs-string">"address length should be greater than 10"</span>;
        }
        <span class="hljs-keyword">return</span> errMessage;
    }

    isValidEmail(email) {
        <span class="hljs-keyword">var</span> re = <span class="hljs-regexp">/^(([^&lt;&gt;()\[\]\\.,;:\s@"]+(\.[^&lt;&gt;()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/</span>;
        <span class="hljs-keyword">return</span> re.test(<span class="hljs-built_in">String</span>(email).toLowerCase());
    }


}
</code></pre>
<p>In the above code:</p>
<ul>
<li>We have created a method validate which takes the parameter user. It validates the user &amp; returns the error message if there is a validation error, otherwise null.</li>
<li>We are validating data inside the check method, which is part of guard lifecycle. We are validating the user inside it by calling the method validate.<br>If the user is valid, then we are passing the user value by using the "data" property and returning null. Returning null means guard has allowed this request and the worker should be called.</li>
<li>If a user is not valid, we are returning an error message as a text response with the HTTP code "Bad Request". In this case, execution will stop here and the worker won't be called.</li>
</ul>
<p>In order to activate this guard for the method addUser, we need to add this on top of addUser. The guard is added by using the decorator "Guards". So let's add the guard:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Post])
@Route(<span class="hljs-string">"/"</span>)
@Guards([UserValidatorGuard])
<span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> newUser = service.addUser(<span class="hljs-built_in">this</span>.data.user);
    <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre>
<p>In the above code:</p>
<ul>
<li>I have added the guard, “UserValidatorGuard” using the decorator Guards.</li>
<li>With the guard in the process, we don't need to parse the data from the body anymore inside the worker. Rather, we are reading it from this.data which we are passing from "UserValidatorGuard".</li>
<li>The method “addUser” will only be called when Guard allows, which means all data is valid.</li>
</ul>
<p>One thing to note is that the method "addUser" looks very light after using a component, and it's doing validation too. You can add multiple guards to a worker which gives you the ability to modularize your code into multiple guards and use that guard at multiple places.</p>
<blockquote>
<p>Isn't this cool :D?</p>
</blockquote>
<p>Let's try adding a user with some invalid data:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-23-21-37.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see in the screenshot, I have tried sending a request without a password. The result is - "password should be minimum 5 characters". So it means that guard is activated and working perfectly.</p>
<h3 id="heading-put">PUT</h3>
<p>Let’s add another method - “updateUser” with route “/” , guard “UserValidatorGuard” (for validation of user) and most important - worker with http method “PUT”.</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Put])
@Guards([UserValidatorGuard])
@Route(<span class="hljs-string">"/"</span>)
<span class="hljs-keyword">async</span> updateUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> user = <span class="hljs-built_in">this</span>.data.user;
    <span class="hljs-keyword">const</span> userUpdated = service.updateUser(user);
    <span class="hljs-keyword">if</span> (userUpdated === <span class="hljs-literal">true</span>) {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"user updated"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"invalid user"</span>);
    }
}
</code></pre>
<p>The updated code is similar to the addUser code except functionality wise it is updating the data. Here, we have reutilized UserValidatorGuard to validate data.</p>
<h3 id="heading-delete">DELETE</h3>
<p>In order to delete data, user needs to pass the id of the user. This can be passed by:</p>
<ul>
<li>Sending data in body just like we did for add &amp; update - {id:1}</li>
<li>Sending data in query string - ?id=1</li>
<li>Sending data in route - for this, we need to customize our route - "/user/1"</li>
</ul>
<p>We have already implemented getting data from body. So let's see other two ways:</p>
<p><strong>Sending Data in Query String</strong></p>
<p>Let's create a method "removeByQueryString" and paste the below code:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Delete])
@Route(<span class="hljs-string">"/"</span>)
<span class="hljs-keyword">async</span> removeByQueryString(@Singleton(UserService) service) {
    <span class="hljs-comment">// taking id from query string</span>
    <span class="hljs-keyword">const</span> userId = <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">this</span>.query.id);
    <span class="hljs-keyword">const</span> user = service.getUser(userId);
    <span class="hljs-keyword">if</span> (user != <span class="hljs-literal">null</span>) {
        service.removeUser(userId);
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"user deleted"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"invalid user"</span>, <span class="hljs-number">404</span>);
    }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-23-40-34.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Sending Data in Route</strong></p>
<p>You can parameterise the route by using "{var}" in a route. Let's see how.</p>
<p>Let's create another method "removeByRoute" and paste the below code:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Delete])
@Route(<span class="hljs-string">"/{id}"</span>)
<span class="hljs-keyword">async</span> removeByRoute(@Singleton(UserService) service) {

    <span class="hljs-comment">// taking id from route</span>
    <span class="hljs-keyword">const</span> userId = <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">this</span>.param.id);

    <span class="hljs-keyword">const</span> user = service.getUser(userId);
    <span class="hljs-keyword">if</span> (user != <span class="hljs-literal">null</span>) {
        service.removeUser(userId);
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"user deleted"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"invalid user"</span>);
    }
}
</code></pre>
<p>The above code is exactly the same as removeByQueryString except that it is extracting the id from the route and using parameter in route i.e., "/{id}" where id is parameter.</p>
<p>Let's test this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-23-46-42.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>So we have finally created a REST API for all the funtionalities except GETting a particular user by id. I will leave that to you for practice.</p>
<h2 id="heading-points-of-interest">POINTS OF INTEREST</h2>
<p>Q: How do we add authentication to "UserController", so that any unauthenticated request can't call the "/user" end point.</p>
<p>A: There are multiple approaches for this: </p>
<ul>
<li>We can check in every worker for authentication. (BAD - so much extra work and code repetition)</li>
<li>Create a Guard component and assign to every worker . (GOOD) </li>
<li>Create a <a target="_blank" href="http://fortjs.info/tutorial/shield/">Shield</a> component and assign to controller. Shield is a security layer similar to guard but works on top of controller, so if shield rejects then controller is not initiated. (BEST)</li>
</ul>
<p>Take a look at the FortJs authentication docs - <a target="_blank" href="http://fortjs.info/tutorial/authentication/">http://fortjs.info/tutorial/authentication/</a></p>
<h2 id="heading-references">REFERENCES</h2>
<ul>
<li><a target="_blank" href="http://fortjs.info/">http://fortjs.info/</a></li>
<li><a target="_blank" href="https://medium.com/fortjs">https://medium.com/fortjs</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Manipulate Arrays in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ An important part of any programming language. Most times we need to do several operations on arrays, hence this article. In this article, I would show you various methods of manipulating arrays in JavaScript [^^] What are Arrays in JavaScript? Befor... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/manipulating-arrays-in-javascript/</link>
                <guid isPermaLink="false">66d84e26f6b5e038a1bde7cf</guid>
                
                    <category>
                        <![CDATA[ 100DaysOfCode ]]>
                    </category>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bolaji Ayodeji ]]>
                </dc:creator>
                <pubDate>Thu, 13 Jun 2019 12:51:09 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/06/1_EK3RyHqvMS-ZIy9UyNMxTA--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>An important part of any programming language. Most times we need to do several operations on arrays, hence this article.</p>
<p>In this article, I would show you various methods of manipulating arrays in JavaScript [^^]</p>
<h3 id="heading-what-are-arrays-in-javascript">What are Arrays in JavaScript?</h3>
<p>Before we proceed, you need to understand what arrays really mean.</p>
<blockquote>
<p><em>In JavaScript, an array is a variable that is used to store different data types. It basically stores different elements in one box and can be later assesssed with the variable.</em></p>
</blockquote>
<p>Declaring an array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myBox = [];   <span class="hljs-comment">// Initial Array declaration in JS</span>
</code></pre>
<p>Arrays can contain multiple data types</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myBox = [<span class="hljs-string">'hello'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-literal">true</span>, <span class="hljs-string">'hi'</span>];
</code></pre>
<p>Arrays can be manipulated by using several actions known as <strong>methods.</strong> Some of these methods allow us to add, remove, modify and do lots more to arrays.</p>
<p>I would be showing you a few in this article, let’s roll :)</p>
<blockquote>
<p><em>NB: I used</em> <strong><em>Arrow functions</em></strong> in this post, If you don’t know what this means, you should read <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">here</a>. Arrow function is an <strong>ES6 feature</strong>.</p>
</blockquote>
<h3 id="heading-tostring">toString()</h3>
<p>The JavaScript method <code>toString()</code> converts an array to a string separated by a comma.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> colors = [<span class="hljs-string">'green'</span>, <span class="hljs-string">'yellow'</span>, <span class="hljs-string">'blue'</span>];

<span class="hljs-built_in">console</span>.log(colors.toString()); <span class="hljs-comment">// green,yellow,blue</span>
</code></pre>
<h3 id="heading-join">join()</h3>
<p>The JavaScript <code>join()</code> method combines all array elements into a string.</p>
<p>It is similar to <code>toString()</code> method, but here you can specify the separator instead of the default comma.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> colors = [<span class="hljs-string">'green'</span>, <span class="hljs-string">'yellow'</span>, <span class="hljs-string">'blue'</span>];

<span class="hljs-built_in">console</span>.log(colors.join(<span class="hljs-string">'-'</span>)); <span class="hljs-comment">// green-yellow-blue</span>
</code></pre>
<h3 id="heading-concat">concat</h3>
<p>This method combines two arrays together or add more items to an array and then return a new array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> firstNumbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> secondNumbers = [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];
<span class="hljs-keyword">let</span> merged = firstNumbers.concat(secondNumbers);
<span class="hljs-built_in">console</span>.log(merged); <span class="hljs-comment">// [1, 2, 3, 4, 5, 6]</span>
</code></pre>
<h3 id="heading-push">push()</h3>
<p>This method adds items to the end of an array and <strong>changes</strong> the original array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> browsers = [<span class="hljs-string">'chrome'</span>, <span class="hljs-string">'firefox'</span>, <span class="hljs-string">'edge'</span>];
browsers.push(<span class="hljs-string">'safari'</span>, <span class="hljs-string">'opera mini'</span>);
<span class="hljs-built_in">console</span>.log(browsers); 
<span class="hljs-comment">// ["chrome", "firefox", "edge", "safari", "opera mini"]</span>
</code></pre>
<h3 id="heading-pop">pop()</h3>
<p>This method removes the last item of an array and <strong>returns</strong> it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> browsers = [<span class="hljs-string">'chrome'</span>, <span class="hljs-string">'firefox'</span>, <span class="hljs-string">'edge'</span>];
browsers.pop(); <span class="hljs-comment">// "edge"</span>
<span class="hljs-built_in">console</span>.log(browsers); <span class="hljs-comment">// ["chrome", "firefox"]</span>
</code></pre>
<h3 id="heading-shift">shift()</h3>
<p>This method removes the first item of an array and <strong>returns</strong> it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> browsers = [<span class="hljs-string">'chrome'</span>, <span class="hljs-string">'firefox'</span>, <span class="hljs-string">'edge'</span>];
browsers.shift(); <span class="hljs-comment">// "chrome"</span>
<span class="hljs-built_in">console</span>.log(browsers); <span class="hljs-comment">// ["firefox", "edge"]</span>
</code></pre>
<h3 id="heading-unshift">unshift()</h3>
<p>This method adds an item(s) to the beginning of an array and <strong>changes</strong> the original array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> browsers = [<span class="hljs-string">'chrome'</span>, <span class="hljs-string">'firefox'</span>, <span class="hljs-string">'edge'</span>];
browsers.unshift(<span class="hljs-string">'safari'</span>);
<span class="hljs-built_in">console</span>.log(browsers); <span class="hljs-comment">//  ["safari", "chrome", "firefox", "edge"]</span>
</code></pre>
<blockquote>
<p><em>You can also add multiple items at once</em></p>
</blockquote>
<h3 id="heading-splice">splice()</h3>
<p>This method <strong>changes</strong> an array, by adding, removing and inserting elements.</p>
<p>The syntax is:</p>
<pre><code class="lang-python">array.splice(index[, deleteCount, element1, ..., elementN])
</code></pre>
<ul>
<li><p><code>**Index**</code> here is the starting point for removing elements in the array</p>
</li>
<li><p><code>**deleteCount**</code> is the number of elements to be deleted from that index</p>
</li>
<li><p><code>**element1, …, elementN**</code> is the element(s) to be added</p>
</li>
</ul>
<p><strong><em>Removing items</em></strong></p>
<blockquote>
<p><em>after running</em> <strong><em>splice()</em></strong> , it returns the array with the item(s) removed and removes it from the original array.</p>
</blockquote>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> colors = [<span class="hljs-string">'green'</span>, <span class="hljs-string">'yellow'</span>, <span class="hljs-string">'blue'</span>, <span class="hljs-string">'purple'</span>];
colors.splice(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(colors); <span class="hljs-comment">// ["purple"]</span>
<span class="hljs-comment">// deletes ["green", "yellow", "blue"]</span>
</code></pre>
<blockquote>
<p><strong><em>NB</em></strong>: The deleteCount does not include the last index in range.</p>
</blockquote>
<p>If the second parameter is not declared, every element starting from the given index will be removed from the array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> colors = [<span class="hljs-string">'green'</span>, <span class="hljs-string">'yellow'</span>, <span class="hljs-string">'blue'</span>, <span class="hljs-string">'purple'</span>];
colors.splice(<span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(colors); <span class="hljs-comment">// ["green", "yellow", "blue"]</span>
<span class="hljs-comment">// deletes ['purple']</span>
</code></pre>
<p>In the next example we will remove 3 elements from the array and replace them with more items:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> schedule = [<span class="hljs-string">'I'</span>, <span class="hljs-string">'have'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'meeting'</span>, <span class="hljs-string">'tommorrow'</span>];
<span class="hljs-comment">// removes 4 first elements and replace them with another</span>
schedule.splice(<span class="hljs-number">0</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'we'</span>, <span class="hljs-string">'are'</span>, <span class="hljs-string">'going'</span>, <span class="hljs-string">'to'</span>, <span class="hljs-string">'swim'</span>);
<span class="hljs-built_in">console</span>.log(schedule); 
<span class="hljs-comment">// ["we", "are", "going", "to", "swim", "tommorrow"]</span>
</code></pre>
<p><strong><em>Adding items</em></strong></p>
<p>To add items, we need to set the <code>deleteCount</code> to zero</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> schedule = [<span class="hljs-string">'I'</span>, <span class="hljs-string">'have'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'meeting'</span>, <span class="hljs-string">'with'</span>];
<span class="hljs-comment">// adds 3 new elements to the array</span>
schedule.splice(<span class="hljs-number">5</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'some'</span>, <span class="hljs-string">'clients'</span>, <span class="hljs-string">'tommorrow'</span>);
<span class="hljs-built_in">console</span>.log(schedule); 
<span class="hljs-comment">// ["I", "have", "a", "meeting", "with", "some", "clients", "tommorrow"]</span>
</code></pre>
<h3 id="heading-slice">slice()</h3>
<blockquote>
<p><em>This method is similar to</em> <code>splice()</code> but very different. It returns subarrays instead of substrings.</p>
</blockquote>
<p>This method <strong>copies</strong> a given part of an array and returns that copied part as a new array. <strong>It does not change the original array.</strong></p>
<p>The syntax is:</p>
<pre><code class="lang-python">array.slice(start, end)
</code></pre>
<p>Here’s a basic example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</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>]
numbers.slice(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>)
<span class="hljs-comment">// returns [1, 2, 3]</span>
<span class="hljs-built_in">console</span>.log(numbers) <span class="hljs-comment">// returns the original array</span>
</code></pre>
<p>The best way to use <code>slice()</code> is to assign it to a new variable.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> message = <span class="hljs-string">'congratulations'</span>
<span class="hljs-keyword">const</span> abbrv = message.slice(<span class="hljs-number">0</span>, <span class="hljs-number">7</span>) + <span class="hljs-string">'s!'</span>; 
<span class="hljs-built_in">console</span>.log(abbrv) <span class="hljs-comment">// returns "congrats!"</span>
</code></pre>
<h3 id="heading-split">split()</h3>
<p>This method is used for <strong>strings</strong>. It divides a string into substrings and returns them as an array.</p>
<p>Here’s the syntax:string.split(separator, limit);</p>
<ul>
<li><p>The <code>**separator**</code> here defines how to split a string either by a comma.</p>
</li>
<li><p>The <code>**limit**</code> determines the number of splits to be carried out</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> firstName = <span class="hljs-string">'Bolaji'</span>;
<span class="hljs-comment">// return the string as an array</span>
firstName.split() <span class="hljs-comment">// ["Bolaji"]</span>
</code></pre>
<p>another example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> firstName = <span class="hljs-string">'hello, my name is bolaji, I am a dev.'</span>;
firstName.split(<span class="hljs-string">','</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// ["hello", " my name is bolaji"]</span>
</code></pre>
<blockquote>
<p><strong><em>NB:</em></strong> <em>If we declare an empty array, like this</em> <code>firstName.split('');</code> <em>then each item in the string will be divided as substrings</em>:</p>
</blockquote>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> firstName = <span class="hljs-string">'Bolaji'</span>;
firstName.split(<span class="hljs-string">''</span>) <span class="hljs-comment">// ["B", "o", "l", "a", "j", "i"]</span>
</code></pre>
<h3 id="heading-indexof">indexOf()</h3>
<p>This method looks for an item in an array and returns <strong>the index</strong> where it was found else it returns <code>-1</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> fruits = [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'orange'</span>, <span class="hljs-literal">false</span>, <span class="hljs-number">3</span>]
fruits.indexOf(<span class="hljs-string">'orange'</span>); <span class="hljs-comment">// returns 1</span>
fruits.indexOf(<span class="hljs-number">3</span>); <span class="hljs-comment">// returns 3</span>
friuts.indexOf(<span class="hljs-literal">null</span>); <span class="hljs-comment">// returns -1 (not found)</span>
</code></pre>
<h3 id="heading-lastindexof">lastIndexOf()</h3>
<p>This method works the same way <strong>indexOf()</strong> does except that it works from right to left. It returns the last index where the item was found</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> fruits = [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'orange'</span>, <span class="hljs-literal">false</span>, <span class="hljs-number">3</span>, <span class="hljs-string">'apple'</span>]
fruits.lastIndexOf(<span class="hljs-string">'apple'</span>); <span class="hljs-comment">// returns 4</span>
</code></pre>
<h3 id="heading-filter">filter()</h3>
<p>This method creates a new array if the items of an array pass a certain condition.</p>
<p>The syntax is:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> results = array.filter(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item, index, array</span>) </span>{
  <span class="hljs-comment">// returns true if the item passes the filter</span>
});
</code></pre>
<p>Example:</p>
<p>Checks users from Nigeria</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> countryCode = [<span class="hljs-string">'+234'</span>, <span class="hljs-string">'+144'</span>, <span class="hljs-string">'+233'</span>, <span class="hljs-string">'+234'</span>];
<span class="hljs-keyword">const</span> nigerian = countryCode.filter( <span class="hljs-function"><span class="hljs-params">code</span> =&gt;</span> code === <span class="hljs-string">'+234'</span>);
<span class="hljs-built_in">console</span>.log(nigerian); <span class="hljs-comment">// ["+234", "+234"]</span>
</code></pre>
<h3 id="heading-map">map()</h3>
<p>This method creates a new array by manipulating the values in an array.</p>
<p>Example:</p>
<p>Displays usernames on a page. (Basic friend list display)</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> userNames = [<span class="hljs-string">'tina'</span>, <span class="hljs-string">'danny'</span>, <span class="hljs-string">'mark'</span>, <span class="hljs-string">'bolaji'</span>];
<span class="hljs-keyword">const</span> display = userNames.map(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
<span class="hljs-keyword">return</span> <span class="hljs-string">'&lt;li&gt;'</span> + item + <span class="hljs-string">'&lt;/li&gt;'</span>;
})
<span class="hljs-keyword">const</span> render = <span class="hljs-string">'&lt;ul&gt;'</span> + display.join(<span class="hljs-string">''</span>) + <span class="hljs-string">'&lt;/ul&gt;'</span>;
<span class="hljs-built_in">document</span>.write(render);
</code></pre>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*obuBZKFb5vKmUP7D4TX2XA.png" alt="Image" width="344" height="134" loading="lazy"></p>
<p>another example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// adds dollar sign to numbers</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">10</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>];
<span class="hljs-keyword">const</span> dollars = numbers.map( <span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> <span class="hljs-string">'$'</span> + number);
<span class="hljs-built_in">console</span>.log(dollars);
<span class="hljs-comment">// ['$10', '$3', '$4', '$6'];</span>
</code></pre>
<h3 id="heading-reduce">reduce()</h3>
<p>This method is good for calculating totals.</p>
<p><strong>reduce()</strong> is used to calculate a single value based on an array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> value = array.reduce(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">previousValue, item, index, array</span>) </span>{
  <span class="hljs-comment">// ...</span>
}, initial);
</code></pre>
<p>example:</p>
<blockquote>
<p><em>To loop through an array and sum all numbers in the array up, we can use the for of loop.</em></p>
</blockquote>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">100</span>, <span class="hljs-number">300</span>, <span class="hljs-number">500</span>, <span class="hljs-number">70</span>];
<span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n <span class="hljs-keyword">of</span> numbers) {
sum += n;
}
<span class="hljs-built_in">console</span>.log(sum);
</code></pre>
<p>Here’s how to do same with <code>reduce()</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">100</span>, <span class="hljs-number">300</span>, <span class="hljs-number">500</span>, <span class="hljs-number">70</span>];
<span class="hljs-keyword">const</span> sum = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">accummulator, value</span>) =&gt;</span>
accummulator + value
, <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(sum); <span class="hljs-comment">// 970</span>
</code></pre>
<blockquote>
<p><em>If you omit the initial value, the total will by default start from the first item in the array.</em></p>
</blockquote>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">100</span>, <span class="hljs-number">300</span>, <span class="hljs-number">500</span>, <span class="hljs-number">70</span>];
<span class="hljs-keyword">const</span> sum = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">accummulator, value</span>) =&gt;</span> accummulator + value);
<span class="hljs-built_in">console</span>.log(sum); <span class="hljs-comment">// still returns 970</span>
</code></pre>
<p>The snippet below shows how the <strong>reduce()</strong> method works with all four arguments.</p>
<p><strong>source: MDN Docs</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*Cbd9qR_vy71qZjEQCFpCLQ.png" alt="Image" width="800" height="476" loading="lazy"></p>
<p>More insights into the <strong>reduce()</strong> method and various ways of using it can be found <a target="_blank" href="https://medium.freecodecamp.org/reduce-f47a7da511a9">here</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">here</a>.</p>
<h3 id="heading-foreach">forEach()</h3>
<p>This method is good for iterating through an array.</p>
<p>It applies a function on all items in an array</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> colors = [<span class="hljs-string">'green'</span>, <span class="hljs-string">'yellow'</span>, <span class="hljs-string">'blue'</span>];
colors.forEach(<span class="hljs-function">(<span class="hljs-params">item, index</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(index, item));
<span class="hljs-comment">// returns the index and the every item in the array</span>
<span class="hljs-comment">// 0 "green"</span>
<span class="hljs-comment">// 1 "yellow"</span>
<span class="hljs-comment">// 2 "blue"</span>
</code></pre>
<p>iteration can be done without passing the index argument</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> colors = [<span class="hljs-string">'green'</span>, <span class="hljs-string">'yellow'</span>, <span class="hljs-string">'blue'</span>];
colors.forEach(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(item));
<span class="hljs-comment">// returns every item in the array</span>
<span class="hljs-comment">// "green"</span>
<span class="hljs-comment">// "yellow"</span>
<span class="hljs-comment">// "blue"</span>
</code></pre>
<h3 id="heading-every">every()</h3>
<p>This method checks if all items in an array pass the specified condition and return<code>true</code> if passed, else <code>false</code>.</p>
<blockquote>
<p><em>check if all numbers are positive</em></p>
</blockquote>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> allPositive = numbers.every(<span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> {
<span class="hljs-keyword">return</span> value &gt;= <span class="hljs-number">0</span>;
})
<span class="hljs-built_in">console</span>.log(allPositive); <span class="hljs-comment">// would return false</span>
</code></pre>
<h3 id="heading-some">some()</h3>
<p>This method checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.</p>
<blockquote>
<p><em>c_hecks if at least one number is positive</em>_</p>
</blockquote>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> atLeastOnePositive = numbers.some(<span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> {
<span class="hljs-keyword">return</span> value &gt;= <span class="hljs-number">0</span>;
})
<span class="hljs-built_in">console</span>.log(atLeastOnePositive); <span class="hljs-comment">// would return true</span>
</code></pre>
<h3 id="heading-includes">includes()</h3>
<p>This method checks if an array contains a certain item. It is similar to <code>.some()</code>, but instead of looking for a specific condition to pass, it checks if the array contains a specific item.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> users = [<span class="hljs-string">'paddy'</span>, <span class="hljs-string">'zaddy'</span>, <span class="hljs-string">'faddy'</span>, <span class="hljs-string">'baddy'</span>];
users.includes(<span class="hljs-string">'baddy'</span>); <span class="hljs-comment">// returns true</span>
</code></pre>
<p>If the item is not found, it returns <code>false</code></p>
<hr>
<p>There are more array methods, this is just a few of them. Also, there are tons of other actions that can be performed on arrays, try checking MDN docs <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/">here</a>for deeper insights.</p>
<h3 id="heading-summary">Summary</h3>
<ul>
<li><p><strong>toString()</strong> converts an array to a string separated by a comma.</p>
</li>
<li><p><strong>join()</strong> combines all array elements into a string.</p>
</li>
<li><p><strong>concat</strong> combines two arrays together or add more items to an array and then return a new array.</p>
</li>
<li><p><strong>push()</strong> adds item(s) to the end of an array and <strong>changes</strong> the original array.</p>
</li>
<li><p><strong>pop()</strong> removes the last item of an array and <strong>returns</strong> it</p>
</li>
<li><p><strong>shift()</strong> removes the first item of an array and <strong>returns</strong> it</p>
</li>
<li><p><strong>unshift()</strong> adds an item(s) to the beginning of an array and <strong>changes</strong> the original array.</p>
</li>
<li><p><strong>splice()</strong> c<strong>hanges</strong> an array, by adding, removing and inserting elements.</p>
</li>
<li><p><strong>slice()</strong> copies a given part of an array and returns that copied part as a new array. <strong>It does not change the original array.</strong></p>
</li>
<li><p><strong>split()</strong> divides a string into substrings and returns them as an array.</p>
</li>
<li><p><strong>indexOf()</strong> looks for an item in an array and returns <strong>the index</strong> where it was found else it returns <code>-1</code></p>
</li>
<li><p><strong>lastIndexOf()</strong> looks for an item from right to left and returns the last index where the item was found.</p>
</li>
<li><p><strong>filter()</strong> creates a new array if the items of an array pass a certain condition.</p>
</li>
<li><p><strong>map()</strong> creates a new array by manipulating the values in an array.</p>
</li>
<li><p><strong>reduce()</strong> calculates a single value based on an array.</p>
</li>
<li><p><strong>forEach()</strong> iterates through an array, it applies a function on all items in an array</p>
</li>
<li><p><strong>every()</strong> checks if all items in an array pass the specified condition and return true if passed, else false.</p>
</li>
<li><p><strong>some()</strong> checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.</p>
</li>
<li><p><strong>includes()</strong> checks if an array contains a certain item.</p>
</li>
</ul>
<hr>
<p>Let’s wrap it here; Arrays are powerful and using methods to manipulate them creates the Algorithms real-world applications use.</p>
<p>Let's do a create a small function, one that converts a post title into a urlSlug.</p>
<blockquote>
<p><strong><em>URL slug</em></strong> is the exact address of a specific page or post on your site.</p>
</blockquote>
<p>When you write an article on <strong>Freecodecamp News</strong> or any other writing platform, your post title is automatically converted to a slug with white spaces removed, characters turned to lowercase and each word in the title separated by a hyphen.</p>
<p>Here’s a basic function that does that using some of the methods we learnt just now.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> url = <span class="hljs-string">'https://bolajiayodeji.com/'</span>
<span class="hljs-keyword">const</span> urlSlug = <span class="hljs-function">(<span class="hljs-params">postTitle</span>) =&gt;</span> {
<span class="hljs-keyword">let</span> postUrl = postTitle.toLowerCase().split(<span class="hljs-string">' '</span>);
<span class="hljs-keyword">let</span> postSlug = <span class="hljs-string">`<span class="hljs-subst">${url}</span>`</span> + postUrl.join(<span class="hljs-string">'-'</span>);
<span class="hljs-keyword">return</span> postSlug;
}
<span class="hljs-keyword">let</span> postTitle = <span class="hljs-string">'Introduction to Chrome Lighthouse'</span>
<span class="hljs-built_in">console</span>.log(urlSlug(postTitle));
<span class="hljs-comment">// https://bolajiayodeji.com/introduction-to-chrome-lighthouse</span>
</code></pre>
<p>in <code>postUrl</code>, we convert the string to lowercase then we use the **split()**method to convert the string into substrings and returns it in an array</p>
<pre><code class="lang-python">[<span class="hljs-string">"introduction"</span>, <span class="hljs-string">"to"</span>, <span class="hljs-string">"chrome"</span>, <span class="hljs-string">"lighthouse"</span>]
</code></pre>
<p>in <code>post slug</code> we join the returned array with a hyphen and then concatenate it to the category string and main <code>url</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> postSlug = <span class="hljs-string">`<span class="hljs-subst">${url}</span>`</span> + postUrl.join(<span class="hljs-string">'-'</span>);
postUrl.join(<span class="hljs-string">'-'</span>) <span class="hljs-comment">// introduction-to-chrome-lighthouse</span>
</code></pre>
<p>That’s it, pretty simple, right? :)</p>
<hr>
<p>If you’re just getting started with JavaScript, you should check this repository <a target="_blank" href="https://github.com/BolajiAyodeji/js-code-snippets">here</a>, I’m compiling a list of basic JavaScript snippets ranging from</p>
<ul>
<li><p>Arrays</p>
</li>
<li><p>Control flow</p>
</li>
<li><p>Functions</p>
</li>
<li><p>Objects</p>
</li>
<li><p>Operators</p>
</li>
</ul>
<p>Don’t forget to Star and share! :)</p>
<p>PS: This article was first published on my blog <a target="_blank" href="https://www.bolajiayodeji.com/manipulating-arrays-in-javascript/">here</a></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
