<?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[ Dario Di Cillo - 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[ Dario Di Cillo - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 16 May 2026 22:22:23 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/DarioDC/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Array Tutorial – Array Methods in JS ]]>
                </title>
                <description>
                    <![CDATA[ Arrays are data structures that are extremely useful and versatile. They're present in many programming languages, and they allow you to store multiple values in a single variable. In this tutorial, we will explore how arrays work in JavaScript, thei... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-array-tutorial-array-methods-in-js/</link>
                <guid isPermaLink="false">66bb91147a6500a14ba5b78d</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dario Di Cillo ]]>
                </dc:creator>
                <pubDate>Mon, 27 Mar 2023 19:45:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/tom-wilson-Em2hPK55o8g-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Arrays are data structures that are extremely useful and versatile. They're present in many programming languages, and they allow you to store multiple values in a single variable.</p>
<p>In this tutorial, we will explore how arrays work in JavaScript, their characteristics, and how to manipulate them using the most common array methods.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-how-to-create-an-array-in-javascript">How to Create an Array in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-array-indexing">Array Indexing</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-length-property">How to Use the <code>length</code> Property</a></li>
<li><a class="post-section-overview" href="#heading-multidimensional-arrays">Multidimensional Arrays</a> </li>
<li><a class="post-section-overview" href="#heading-sparse-arrays">Sparse Arrays</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compare-arrays-in-javascript">How to Compare Arrays in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-the-spread-operator-vs-the-rest-parameter">The Spread Operator vs the Rest Parameter</a></li>
<li><a class="post-section-overview" href="#heading-destructuring-assignment">Destructuring Assignment</a></li>
<li><a class="post-section-overview" href="#heading-how-to-add-and-remove-elements-from-an-array">How to Add and Remove Elements from an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-combine-arrays">How to Combine Arrays</a> </li>
<li><a class="post-section-overview" href="#heading-how-to-convert-an-array-into-a-string">How to Convert an Array into a String</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compare-arrays">How to Compare Arrays</a></li>
<li><a class="post-section-overview" href="#heading-how-to-copy-an-array">How to Copy an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-search-inside-an-array">How to Search Inside an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-check-if-array-elements-meet-a-condition">How to Check if Array Elements Meet a Condition</a></li>
<li><a class="post-section-overview" href="#heading-how-to-sort-an-array">How to Sort an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-perform-an-operation-on-every-array-element">How to Perform an Operation on Every Array Element</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h1 id="heading-an-introduction-to-arrays-in-js">An Introduction to Arrays in JS</h1>
<p>In JavaScript, an array is an <strong>object</strong> constituted by a group of items having a specific <strong>order</strong>. Arrays can hold values of <strong>mixed</strong> data types and their <strong>size</strong> is <strong>not fixed</strong>.</p>
<h2 id="heading-how-to-create-an-array-in-javascript">How to Create an Array in JavaScript</h2>
<p>You can create an array using a <strong>literal syntax</strong> – specifying its content inside square brackets, with each item separated by a comma.</p>
<p>Let's create an array of strings, called <code>nobleGases</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>];

<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn']</span>
</code></pre>
<p>Alternatively, you can use the <code>Array()</code> <strong>constructor</strong>, passing the elements to put inside the array as arguments.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = <span class="hljs-built_in">Array</span>(<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>);

<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn']</span>
</code></pre>
<h2 id="heading-array-indexing">Array Indexing</h2>
<p>Each element inside an array is identified by its numeric <strong>index</strong> or position – starting from zero (not 1) in JavaScript, as in many programming languages. We can access elements through <strong>bracket notation</strong>, specifying the index inside square brackets. </p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>];
nobleGases[<span class="hljs-number">0</span>]; <span class="hljs-comment">// 'He'</span>
nobleGases[<span class="hljs-number">1</span>]; <span class="hljs-comment">// 'Ne'</span>
nobleGases[<span class="hljs-number">2</span>]; <span class="hljs-comment">// 'Ar'</span>
nobleGases[<span class="hljs-number">3</span>]; <span class="hljs-comment">// 'Kr'</span>
nobleGases[<span class="hljs-number">4</span>]; <span class="hljs-comment">// 'Xn'</span>
nobleGases[<span class="hljs-number">5</span>]; <span class="hljs-comment">// undefined</span>
</code></pre>
<p>When you try to access a value out of the index range, you get <code>undefined</code> as the return value. As you can see, in the example above no value is stored at index 5.</p>
<p>JavaScript arrays are <strong>not fixed in size</strong>. They can grow and shrink according to their content. You can easily verify this by trying to assign <code>nobleGases[5]</code> a value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>];
nobleGases[<span class="hljs-number">5</span>] = <span class="hljs-string">'Rn'</span>;
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn', 'Rn']</span>
</code></pre>
<p>Now, <code>nobleGases</code> holds one more value, as you can see in the output.</p>
<h2 id="heading-how-to-use-the-length-property">How to Use the <code>length</code> Property</h2>
<p>You can check the number of elements contained inside an array using the <code>length</code> property, through <strong>dot notation</strong>:</p>
<pre><code class="lang-js">nobleGases.length; <span class="hljs-comment">// 6</span>
</code></pre>
<p>The array length will be the value of the index of the last element inside the array + 1, since the indexing starts at zero.</p>
<h2 id="heading-multidimensional-arrays">Multidimensional Arrays</h2>
<p>JavaScript arrays can hold any allowed values, arrays included. An array inside another array is called a <strong>nested</strong> array. This situation creates the possibility of many array objects nested at different depths. Here's an example of a three-dimensional array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> elements = [[[<span class="hljs-string">'H'</span>, <span class="hljs-string">'Li'</span>, <span class="hljs-string">'Na'</span>], [<span class="hljs-string">'Be'</span>, <span class="hljs-string">'Mg'</span>]], [[<span class="hljs-string">'B'</span>, <span class="hljs-string">'Al'</span>], [<span class="hljs-string">'C'</span>, <span class="hljs-string">'Si'</span>]]];
</code></pre>
<p>You can access the different elements by repeating the bracket syntax with the indexes corresponding to the elements you are interested in, to go deeper and deeper. Like so:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(elements[<span class="hljs-number">0</span>]); <span class="hljs-comment">// [['H', 'Li', 'Na'], ['Be', 'Mg']]</span>

<span class="hljs-built_in">console</span>.log(elements[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>]); <span class="hljs-comment">// ['H', 'Li', 'Na']</span>

<span class="hljs-built_in">console</span>.log(elements[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>][<span class="hljs-number">0</span>]); <span class="hljs-comment">// 'H'</span>
</code></pre>
<h2 id="heading-sparse-arrays">Sparse Arrays</h2>
<p>Sparse arrays are arrays containing <strong>empty</strong> <strong>slots</strong>. For example, if you mistype two consecutive commas when creating an array, you will end up with a sparse array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> firstGroup = [<span class="hljs-string">'H'</span>, <span class="hljs-string">'Li'</span>, <span class="hljs-string">'Na'</span>,, <span class="hljs-string">'K'</span>, <span class="hljs-string">'Rb'</span>, <span class="hljs-string">'Cs'</span>];
<span class="hljs-built_in">console</span>.log(firstGroup);
<span class="hljs-comment">// ['H', 'Li', 'Na', empty, 'K', 'Rb', 'Cs']</span>
</code></pre>
<p>As you can see, between <code>'Na'</code> and <code>'K'</code> there is an <code>empty</code> value. This can be shown in different ways, depending on the coding environment. But it's not the same as having an <code>undefined</code> value.</p>
<p>Sparse arrays can also be created by directly changing the <code>length</code> property or by assignment to an index greater than the length:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Increasing the length property</span>
firstGroup.length = <span class="hljs-number">11</span>;
<span class="hljs-built_in">console</span>.log(firstGroup);
<span class="hljs-comment">// ['H', 'Li', 'Na', empty, 'K', 'Rb', 'Cs', empty × 4]</span>

<span class="hljs-comment">// Assigning an element to an index greater than the length</span>
firstGroup[<span class="hljs-number">15</span>] = <span class="hljs-string">'Fr'</span>;
<span class="hljs-built_in">console</span>.log(firstGroup);
<span class="hljs-comment">// ['H', 'Li', 'Na', empty, 'K', 'Rb', 'Cs', empty × 8, 'Fr']</span>
</code></pre>
<p>Depending on the operation performed on a sparse array, empty slots <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#array_methods_and_empty_slots">can act as <code>undefined</code> or can be skipped</a>. </p>
<h2 id="heading-how-to-compare-arrays-in-javascript">How to Compare Arrays in JavaScript</h2>
<p>JavaScript arrays are objects, and if you try to compare two objects, the comparison takes place considering their <strong>references</strong> – and not their actual <strong>values</strong>.</p>
<p>This means that you could try to compare two arrays containing the same elements – and so, that are apparently equal – like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dough1 = [<span class="hljs-string">'flour'</span>, <span class="hljs-string">'water'</span>, <span class="hljs-string">'yeast'</span>, <span class="hljs-string">'salt'</span>];
<span class="hljs-keyword">let</span> dough2 = [<span class="hljs-string">'flour'</span>, <span class="hljs-string">'water'</span>, <span class="hljs-string">'yeast'</span>, <span class="hljs-string">'salt'</span>];

dough1 === dough2; <span class="hljs-comment">// false</span>
</code></pre>
<p>But, according to JavaScript, they are not equal. And even the comparison of two empty arrays, no matter how they're created, would return the same result:</p>
<pre><code class="lang-js">[] === []; <span class="hljs-comment">// false</span>
<span class="hljs-built_in">Array</span>() === <span class="hljs-built_in">Array</span>(); <span class="hljs-comment">// false</span>
</code></pre>
<p>As I mentioned, this happens because <strong>object references are compared</strong>, and not their actual content. And each time you create a new array object, it will have a different reference in memory.</p>
<p>The only way to make this comparison evaluate to <code>true</code> is to make the two arrays point to the same reference. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dough1 = [<span class="hljs-string">'flour'</span>, <span class="hljs-string">'water'</span>, <span class="hljs-string">'yeast'</span>, <span class="hljs-string">'salt'</span>];
<span class="hljs-keyword">let</span> dough2 = dough1;

dough1 === dough2; <span class="hljs-comment">// true</span>
</code></pre>
<p>In the code above, <code>let dough2 = dough1</code> does not mean you are making a copy of <code>dough1</code>. It means the <code>dough2</code> variable will point exactly to the same reference as <code>dough1</code>. They are the same array object.</p>
<p>Having said that, if you want to compare two arrays, you will need to adopt a different strategy. A good approach would be iterating through the array and comparing each element one by one. You can do this with a <code>for</code> loop and some conditional statements:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> compareArr = <span class="hljs-function">(<span class="hljs-params">arr1, arr2</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (arr1.length !== arr2.length) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
    } 
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr1.length; i++) {
        <span class="hljs-keyword">if</span> (arr1[i] !== arr2[i]) {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
};
</code></pre>
<p>In the code snippet above, you can see a function to check if the two arrays are equal. </p>
<ul>
<li>The first step is verifying if the arrays have the same length. If the length is different, they cannot be equal for sure:</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (arr1.length !== arr2.length) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
    }
</code></pre>
<ul>
<li>Then, a <code>for</code> loop iterates through the array and an <code>if</code> statement checks if each element of the first array is different from the element at the corresponding index in the second array:</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr1.length; i++) {
        <span class="hljs-keyword">if</span> (arr1[i] !== arr2[i]) {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
        }
    }
</code></pre>
<ul>
<li>If no difference is caught, the arrays are equal and the function returns <code>true</code>.</li>
</ul>
<p>Here's the result of comparing the two arrays from the beginning of this section with our function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dough1 = [<span class="hljs-string">'flour'</span>, <span class="hljs-string">'water'</span>, <span class="hljs-string">'yeast'</span>, <span class="hljs-string">'salt'</span>];
<span class="hljs-keyword">let</span> dough2 = [<span class="hljs-string">'flour'</span>, <span class="hljs-string">'water'</span>, <span class="hljs-string">'yeast'</span>, <span class="hljs-string">'salt'</span>];

compareArr(dough1, dough2); <span class="hljs-comment">// true</span>
</code></pre>
<p>Note that we can apply this function only to an array containing <strong>primitive</strong> values<em>.</em> If an array contains objects, you should try to figure out the solution that fits your specific problem and deepen the check.</p>
<p>For example, if you know your arrays are nested, like these:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> metal1 = [[<span class="hljs-string">'Li'</span>, <span class="hljs-string">'Na'</span>, <span class="hljs-string">'K'</span>], [<span class="hljs-string">'Be'</span>, <span class="hljs-string">'Mg'</span>, <span class="hljs-string">'Ca'</span>]];
<span class="hljs-keyword">let</span> metal2 = [[<span class="hljs-string">'Li'</span>, <span class="hljs-string">'Na'</span>, <span class="hljs-string">'K'</span>], [<span class="hljs-string">'Be'</span>, <span class="hljs-string">'Mg'</span>, <span class="hljs-string">'Ca'</span>]];
</code></pre>
<p> One possible solution would be the following:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> compareNested = <span class="hljs-function">(<span class="hljs-params">arr1, arr2</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (arr1.length !== arr2.length) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
    } <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr1.length; i++) {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = <span class="hljs-number">0</span>; j &lt; arr1[i].length; j++) {
            <span class="hljs-keyword">if</span> (arr1[i][j] !== arr2[i][j]) {
                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
            }
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
};

compareNested(metal1, metal2); <span class="hljs-comment">// true</span>
</code></pre>
<p>With respect to the previous function, we added an additional <code>for</code> loop. This is enough to compare elements inside the inner arrays.</p>
<p>If you need to compare two arrays of objects:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> albums1 = [
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'Over-Nite Sensation'</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1973</span>},
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'Apostrophe'</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1974</span>},
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'One Size Fits All'</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1975</span>}
];
<span class="hljs-keyword">let</span> albums2 = [
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'Over-Nite Sensation'</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1973</span>},
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'Apostrophe'</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1974</span>},
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'One Size Fits All'</span>, <span class="hljs-attr">year</span>: <span class="hljs-literal">undefined</span>},
];
</code></pre>
<p> You can do something like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> compareArrObj = <span class="hljs-function">(<span class="hljs-params">arr1, arr2</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (arr1.length !== arr2.length) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr1.length; i++) {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Object</span>.keys(arr1[i]).length !== <span class="hljs-built_in">Object</span>.keys(arr2[i]).length) {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
        }
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> prop <span class="hljs-keyword">in</span> arr1[i]) {
            <span class="hljs-keyword">if</span> (arr1[i][prop] !== arr2[i][prop]) {
                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
            }
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
};
</code></pre>
<ul>
<li>Again, the first step is verifying if the arrays have the same length. If the length is different, they cannot be equal.</li>
<li>A <code>for</code> loop iterates through the array and an <code>if</code> statement checks if each object of the first array has a different length from the object at the corresponding index in the second array:</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr1.length; i++) {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Object</span>.keys(arr1[i]).length !== <span class="hljs-built_in">Object</span>.keys(arr2[i]).length) {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
        }
<span class="hljs-comment">//...</span>
}
</code></pre>
<ul>
<li>Then a <code>for</code>...<code>in</code> loop iterates through the properties of the i-th object of the first array. And an <code>if</code> statement checks if the value of each key is different from the value of the corresponding key in the i-th object of the other array:</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> prop <span class="hljs-keyword">in</span> arr1[i]) {
            <span class="hljs-keyword">if</span> (arr1[i][prop] !== arr2[i][prop]) {
                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
            }
        }
</code></pre>
<p>In the end, the result would be:</p>
<pre><code class="lang-js">compareArrObj(albums1, albums2); <span class="hljs-comment">// false</span>
</code></pre>
<p>Because the <code>year</code> value in the third object of <code>albums2</code> is different. If we change it, the result will be <code>true</code>:</p>
<pre><code class="lang-js">albums2[<span class="hljs-number">2</span>][<span class="hljs-string">'year'</span>] = <span class="hljs-number">1975</span>;

compareArrObj(albums1, albums2); <span class="hljs-comment">// true</span>
</code></pre>
<h2 id="heading-the-spread-operator-vs-the-rest-parameter">The Spread Operator vs the Rest Parameter</h2>
<p>The spread operator and the rest parameter have similar syntax (<code>...</code>) but they perform fundamentally different operations. </p>
<p>The <strong>spread</strong> operator enables you to <strong>expand</strong> an array – more generally an iterable object – into its elements. The <strong>rest</strong> parameter allows you to collect an undefined number of arguments into <strong>a single array</strong>.</p>
<h3 id="heading-how-to-use-the-spread-operator">How to Use the Spread Operator</h3>
<p>Later on in this article, we will see some methods to copy an array or to merge different arrays. But using the spread operator is a valid alternative to do the same things.</p>
<p>In the example below, the <code>alkali</code> and <code>alkEarth</code> arrays are merged into a single array using the spread syntax. To do this, you need to list the arrays you want to merge between square brackets, prepending three dots to each one.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> alkali = [<span class="hljs-string">'Li'</span>, <span class="hljs-string">'Na'</span>, <span class="hljs-string">'K'</span>];
<span class="hljs-keyword">let</span> alkEarth = [<span class="hljs-string">'Be'</span>, <span class="hljs-string">'Mg'</span>, <span class="hljs-string">'Ca'</span>];

<span class="hljs-comment">// Merging two arrays with the spread operator</span>
<span class="hljs-keyword">let</span> metals = [...alkali, ...alkEarth];
<span class="hljs-built_in">console</span>.log(metals); <span class="hljs-comment">// ['Li', 'Na', 'K', 'Be', 'Mg', 'Ca']</span>
</code></pre>
<p>Also, you can use the same syntax with only one array, to create a copy of an array:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Copying an array with the spread operator</span>
<span class="hljs-keyword">let</span> metalsCopy = [...metals];
<span class="hljs-built_in">console</span>.log(metalsCopy); <span class="hljs-comment">// ['Li', 'Na', 'K', 'Be', 'Mg', 'Ca']</span>
</code></pre>
<h3 id="heading-how-to-use-the-rest-parameter">How to Use the Rest Parameter</h3>
<p>The rest parameter allows you to collect an undefined number of elements into a single array. The rest parameter needs to be the last in a sequence of function parameters. Also, a function can have only one rest parameter.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f1</span>(<span class="hljs-params">first, second, third, ...others</span>) </span>{
    <span class="hljs-built_in">console</span>.log(first);
    <span class="hljs-built_in">console</span>.log(second);
    <span class="hljs-built_in">console</span>.log(third);
    <span class="hljs-built_in">console</span>.log(others);
};

f1(<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>, <span class="hljs-string">'Rn'</span>); 
<span class="hljs-comment">// He</span>
<span class="hljs-comment">// Ne</span>
<span class="hljs-comment">// Ar</span>
<span class="hljs-comment">// ['Kr', 'Xn', 'Rn']</span>
</code></pre>
<p>In the example above, the <code>f1</code> function is called with six string arguments. And the arguments after the third one are gathered inside the <code>others</code> array by using the rest syntax.</p>
<p>In general, the arguments passed to a function are collected in the <code>arguments</code> object, which is an array-like object and does not support the iterative methods we will see in the next section macro-section of this article.</p>
<p>So, the rest parameter provides a way to easily access the arguments passed to a function in array form, instead of using the <code>arguments</code> object:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f2</span>(<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-built_in">console</span>.log(args);
    <span class="hljs-comment">// you can use an iterative method on the args array</span>
};

f2(<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>, <span class="hljs-string">'Rn'</span>);
<span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn', 'Rn']</span>
</code></pre>
<p>In the example above, we have simply printed the <code>args</code> array, but the advantage here is being able to implement an iterative method on it.</p>
<h2 id="heading-destructuring-assignment">Destructuring Assignment</h2>
<p>The destructing syntax provides a simple way to assign values by unpacking them from an array object. Let's see a practical example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>];
<span class="hljs-keyword">let</span> [firstRow, secondRow,,FourthRow] = nobleGases;
<span class="hljs-built_in">console</span>.log(firstRow); <span class="hljs-comment">// 'He'</span>
<span class="hljs-built_in">console</span>.log(secondRow); <span class="hljs-comment">// 'Ne'</span>
<span class="hljs-built_in">console</span>.log(FourthRow); <span class="hljs-comment">// 'Kr'</span>
<span class="hljs-comment">// 'Ar' is skipped because of the additional comma</span>
</code></pre>
<p>The variables on the left side of the assignment operator are assigned to the value of the corresponding elements of the array on the right. You can skip array elements and go to the next ones by typing more than one comma between each variable name.</p>
<h1 id="heading-common-array-methods-in-js">Common Array Methods in JS</h1>
<p>In JavaScript, arrays are <strong>objects</strong> and possess <strong>properties</strong> and <strong>methods</strong>.</p>
<p>In this section, we will discuss some of the most common array methods you need to know to work efficiently with arrays in JavaScript.</p>
<h2 id="heading-how-to-add-and-remove-elements-from-an-array">How to Add and Remove Elements from an Array</h2>
<p>In this section, you will see the most common ways to add and remove elements from an array in JavaScript. All the following methods <strong>mutate</strong> the original array.</p>
<h3 id="heading-how-to-use-the-push-method">How to Use the <code>push()</code> Method</h3>
<p>Let's consider the example from the indexing section:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>];
nobleGases[<span class="hljs-number">5</span>] = <span class="hljs-string">'Rn'</span>;
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn', 'Rn']</span>
</code></pre>
<p>We have assigned <code>Rn</code> to index <code>5</code> of the <code>nobleGases</code> array using the bracket notation. At the end of the day, we have simply added <code>Rn</code> at the end of that array. </p>
<p>You can obtain the same result using the <code>push()</code> method, and you don't need to know the length of the array for that. You use the dot notation to call <code>push()</code>, indicating the element(s) to append inside the parenthesis. Like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.push(element1, <span class="hljs-comment">/* … ,*/</span> elementN)
</code></pre>
<p>The specified element will be added at the <strong>end</strong> of the array, returning the new array length. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>];
nobleGases.push(<span class="hljs-string">'Rn'</span>); <span class="hljs-comment">// 6</span>
<span class="hljs-comment">// push() returns the length of the modified array</span>
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn', 'Rn']</span>
</code></pre>
<p>You can append multiple elements with <code>push()</code>, indicating their values separated by a comma:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> halogens = [<span class="hljs-string">'F'</span>, <span class="hljs-string">'Cl'</span>];
<span class="hljs-built_in">console</span>.log(halogens); <span class="hljs-comment">// ['F', 'Cl']</span>

halogens.push(<span class="hljs-string">'Br'</span>, <span class="hljs-string">'I'</span>, <span class="hljs-string">'At'</span>); <span class="hljs-comment">// 5</span>
<span class="hljs-comment">// push() returns the length of the modified array</span>
<span class="hljs-built_in">console</span>.log(halogens); <span class="hljs-comment">// ['F', 'Cl', 'Br', 'I', 'At']</span>
</code></pre>
<h3 id="heading-how-to-use-the-unshift-method">How to Use the <code>unshift()</code> Method</h3>
<p>Similar to <code>push()</code>, the <code>unshift()</code> method adds one or more elements to the <strong>beginning</strong> of an array and returns the length of the modified array.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.unshift(element1, <span class="hljs-comment">/* … ,*/</span> elementN)
</code></pre>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> halogens = [<span class="hljs-string">'F'</span>, <span class="hljs-string">'Cl'</span>];
<span class="hljs-built_in">console</span>.log(halogens); <span class="hljs-comment">// ['F', 'Cl']</span>

halogens.unshift(<span class="hljs-string">'Br'</span>, <span class="hljs-string">'I'</span>, <span class="hljs-string">'At'</span>); <span class="hljs-comment">// 5</span>
<span class="hljs-comment">// unshift() returns the length of the modified array</span>
<span class="hljs-built_in">console</span>.log(halogens); <span class="hljs-comment">// ['Br', 'I', 'At', 'F', 'Cl']</span>
</code></pre>
<h3 id="heading-how-to-use-the-pop-method">How to Use the <code>pop()</code> Method</h3>
<p>If you need to remove the <strong>last</strong> element of an array, you can use the <code>pop()</code> method.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.pop()
</code></pre>
<p> It removes only the last element and returns it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>, <span class="hljs-string">'Rn'</span>];
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn', 'Rn']</span>

nobleGases.pop(); <span class="hljs-comment">// 'Rn'</span>
<span class="hljs-comment">// pop() returns the removed element</span>
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn']</span>
</code></pre>
<h3 id="heading-how-to-use-the-shift-method">How to Use the <code>shift()</code> Method</h3>
<p>Similarly, the <code>shift()</code> method removes the <strong>first</strong> element from an array and returns it.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.shift()
</code></pre>
<p>Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>, <span class="hljs-string">'Rn'</span>];
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn', 'Rn']</span>

nobleGases.shift(); <span class="hljs-comment">// 'He'</span>
<span class="hljs-comment">// shift() returns the removed element</span>
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['Ne', 'Ar', 'Kr', 'Xn', 'Rn']</span>
</code></pre>
<h3 id="heading-how-to-use-the-splice-method">How to Use the <code>splice()</code> Method</h3>
<p>If you need to remove one or more elements from a specific position of an array, you can use the <code>splice()</code> method.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.splice(start, count)
</code></pre>
<p>The first parameter of <code>splice()</code> is the <strong>starting index</strong>, while the second is the <strong>number of items to remove</strong> from the array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>, <span class="hljs-string">'Rn'</span>];
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn', 'Rn']</span>

nobleGases.splice(<span class="hljs-number">1</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// ['Ne', 'Ar', 'Kr']</span>
<span class="hljs-comment">// splice() returns an array with removed elements</span>
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Xn', 'Rn']</span>
</code></pre>
<p> So <code>.splice(1, 3)</code> means "start at index = <code>1</code> and remove <code>3</code> elements". The method returns an array containing the elements removed from the original array.</p>
<p>If the second argument is not supplied, the elements are removed until the end.</p>
<p>Using <code>splice()</code> you can add elements, too. </p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.splice(start, count, addition1, <span class="hljs-comment">/* … ,*/</span> additionN)
</code></pre>
<p>If you specify additional arguments – after the starting index and the number of elements to remove – those will be inserted in the indicated position. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Cl'</span>, <span class="hljs-string">'Rn'</span>];
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Cl', 'Rn']</span>

nobleGases.splice(<span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>); <span class="hljs-comment">// ['Cl']</span>
<span class="hljs-comment">// splice() returns an array with removed elements</span>
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn', 'Rn']</span>
</code></pre>
<p>Here, <code>.splice(2, 1, 'Ar', 'Kr', 'Xn')</code> means "start at index = <code>2</code>, remove <code>1</code> element and add the strings <code>'Ar'</code>, <code>'Kr'</code>, <code>'Xn'</code>". The array returned by the method contains the element <code>'Cl'</code>, which was at index = <code>2</code> in the original array.</p>
<p>If you don't need to remove any elements from the array, you can simply use zero as the second argument. The elements will be added starting at the specified index, without removing any item:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Rn'</span>];
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Rn']</span>

nobleGases.splice(<span class="hljs-number">2</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>); <span class="hljs-comment">// []</span>
<span class="hljs-comment">// splice() returns an array with removed elements</span>
<span class="hljs-built_in">console</span>.log(nobleGases); <span class="hljs-comment">// ['He', 'Ne', 'Ar', 'Kr', 'Xn', 'Rn']</span>
</code></pre>
<h2 id="heading-how-to-combine-arrays">How to Combine Arrays</h2>
<h3 id="heading-how-to-use-the-concat-method">How to Use the <code>concat()</code> Method</h3>
<p>If you need to combine two or more arrays – that is create a single array containing each element of the arrays you want to merge – you can use the <code>concat()</code> method. This method does not change the original arrays and returns a new array.</p>
<p>You need to call <code>.concat()</code> on the array that should come first, passing as arguments the arrays you want it to merge with. The order will be reflected in the resulting array.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array1.concat(array2, <span class="hljs-comment">/* … ,*/</span> arrayN)
</code></pre>
<p>Here's an example of combining two and three arrays:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> alkali = [<span class="hljs-string">'Li'</span>, <span class="hljs-string">'Na'</span>, <span class="hljs-string">'K'</span>];
<span class="hljs-keyword">let</span> moreAlkali = [<span class="hljs-string">'Rb'</span>, <span class="hljs-string">'Cs'</span>, <span class="hljs-string">'Fr'</span>];
<span class="hljs-keyword">let</span> alkEarth = [<span class="hljs-string">'Be'</span>, <span class="hljs-string">'Mg'</span>, <span class="hljs-string">'Ca'</span>];

alkali.concat(moreAlkali);
<span class="hljs-comment">// ['Li', 'Na', 'K', 'Rb', 'Cs', 'Fr']</span>

alkali.concat(moreAlkali, alkEarth);
<span class="hljs-comment">// ['Li', 'Na', 'K', 'Rb', 'Cs', 'Fr', 'Be', 'Mg', 'Ca']</span>
</code></pre>
<h3 id="heading-how-to-use-the-push-method-amp-the-spread-operator">How to Use the <code>push()</code> Method &amp; the Spread Operator</h3>
<p>If you don't mind changing the original array you can combine a <code>.push()</code> call to the spread syntax (<code>...</code>) to add all the elements in one or more arrays to the original array. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> alkali = [<span class="hljs-string">'Li'</span>, <span class="hljs-string">'Na'</span>, <span class="hljs-string">'K'</span>];
<span class="hljs-keyword">let</span> moreAlkali = [<span class="hljs-string">'Rb'</span>, <span class="hljs-string">'Cs'</span>, <span class="hljs-string">'Fr'</span>];
<span class="hljs-keyword">let</span> alkEarth = [<span class="hljs-string">'Be'</span>, <span class="hljs-string">'Mg'</span>, <span class="hljs-string">'Ca'</span>];

alkali.push(...moreAlkali); <span class="hljs-comment">// 6</span>
<span class="hljs-built_in">console</span>.log(alkali); <span class="hljs-comment">// ['Li', 'Na', 'K', 'Rb', 'Cs', 'Fr']</span>
</code></pre>
<p>You cannot use <code>push()</code> without the spread syntax in its arguments, unless you want to nest the whole array <code>moreAlkali</code> as the last element of <code>alkali</code>. In that case, the result would be <code>['Li', 'Na', 'K', ['Rb', 'Cs', 'Fr']]</code> – an array composed of 4 elements with the last being an array.</p>
<p>Note that, as we have seen previously, the spread operator alone allows you to merge two or more arrays without causing any mutation. As a continuation of the previous example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> metals = [...alkali, ...alkEarth];
<span class="hljs-built_in">console</span>.log(metals); <span class="hljs-comment">// ['Li', 'Na', 'K', 'Rb', 'Cs', 'Fr', 'Be', 'Mg', 'Ca']</span>
<span class="hljs-built_in">console</span>.log(alkali); <span class="hljs-comment">// ['Li', 'Na', 'K', 'Rb', 'Cs', 'Fr']</span>
</code></pre>
<h2 id="heading-how-to-convert-an-array-into-a-string">How to Convert an Array into a String</h2>
<p>If you need to convert an array into a string, you have different options. And now, we are going to see some of them. Note that the following methods do not mutate the original array.</p>
<h3 id="heading-how-to-use-the-tostring-amp-join-methods">How to Use the <code>toString()</code> &amp; <code>join()</code> Methods</h3>
<p>These methods enable you to convert arrays into strings.</p>
<p>The <code>toString()</code> method is called without a parameter and returns a string representing the content of the array. </p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.toString()
</code></pre>
<p>The <code>join()</code> method takes a separator as the argument, which is used to separate the array elements, in order to form the string.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.join(separator)
</code></pre>
<p>Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [<span class="hljs-string">'pig'</span>, <span class="hljs-string">'dog'</span>, <span class="hljs-string">'sheep'</span>];

animals.toString(); <span class="hljs-comment">// 'pig,dog,sheep'</span>

animals.join(<span class="hljs-string">', '</span>); <span class="hljs-comment">// 'pig, dog, sheep'</span>

animals.join(<span class="hljs-string">' '</span>); <span class="hljs-comment">// 'pig dog sheep'</span>

animals.join(<span class="hljs-string">' * '</span>); <span class="hljs-comment">// 'pig * dog * sheep'</span>
</code></pre>
<p>These two methods have some limitations. If we consider the array in the following example, we can observe a couple of interesting things:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-string">'two'</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-literal">true</span>, {}];

arr.toString(); <span class="hljs-comment">// '1,two,,,true,[object Object]'</span>

arr.join(); <span class="hljs-comment">// '1,two,,,true,[object Object]'</span>
</code></pre>
<p>First, <code>null</code> and <code>undefined</code> result in the same string output (an empty substring). </p>
<p>Second, the string representation of an object is <code>[object Object]</code>. So if you are trying to convert an array containing objects into a string, you should employ another method. Otherwise, you will not be able to see the object content properly.</p>
<h3 id="heading-how-to-use-the-jsonstringify-method">How to Use the <code>JSON.stringify()</code> Method</h3>
<p>If you want to convert an array containing objects into a string, the <code>JSON.stringify()</code> method is what you need. Where the previous methods fail, <code>JSON.stringify()</code> enables you to handle objects properly.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
<span class="hljs-built_in">JSON</span>.stringify(array)
</code></pre>
<p>This method takes a JavaScript value as the argument – in this case the <code>albums</code> array – and converts it to a JSON string.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> albums = [
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'Apostrophe'</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1974</span>},
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'One Size Fits All'</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1975</span>}
];

<span class="hljs-built_in">JSON</span>.stringify(albums);
<span class="hljs-comment">//'[{"artist":"Frank Zappa","title":"Apostrophe","year":1974},{"artist":"Frank Zappa","title":"One Size Fits All","year":1975}]'</span>
</code></pre>
<p>As you can see, the square brackets are retained, so it is often desirable to use this method to create a string from an array.</p>
<h2 id="heading-how-to-compare-arrays">How to Compare Arrays</h2>
<p>Since arrays are objects, their <strong>comparison is based on references</strong>. Not on the actual values.</p>
<p>Before, we have seen some ways to compare arrays by looping through an array and comparing each element.</p>
<p>Another approach for comparing arrays is converting them into strings with one of the previous methods, and then comparing the string representations of the original arrays.</p>
<p>This is quite fast and easy, but sometimes it can lead to unexpected behavior. For example, when <code>null</code> and <code>undefined</code> values are compared.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = [<span class="hljs-number">1</span>, <span class="hljs-literal">null</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> b = [<span class="hljs-number">1</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-number">3</span>];

a[<span class="hljs-number">1</span>] === b[<span class="hljs-number">1</span>]; <span class="hljs-comment">// false</span>

<span class="hljs-built_in">JSON</span>.stringify(a) === <span class="hljs-built_in">JSON</span>.stringify(b); <span class="hljs-comment">// true</span>
</code></pre>
<p>You might think that the comparison between the string representation of <code>a</code> and <code>b</code> would return <code>false</code>, since <code>null</code> and <code>undefined</code> are not equal. But in practice, they are both stringified to null.</p>
<p>In light of this aspect, it would be better to use an iterative technique.</p>
<h3 id="heading-how-to-use-the-every-method">How to Use the <code>every()</code> Method</h3>
<p><code>every()</code> is an iterative method that verifies if all the elements in the array pass a condition implemented by a callback function and it returns <code>true</code> or <code>false</code>.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.every(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {})
</code></pre>
<p>Among its many uses, you can build a simple function to compare arrays containing primitive values with <code>every()</code>, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> compareEvery = <span class="hljs-function">(<span class="hljs-params">arr1, arr2</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> arr1.length === arr2.length &amp;&amp;
    arr1.every(<span class="hljs-function">(<span class="hljs-params">elem, index</span>) =&gt;</span> elem === arr2[index])
}
</code></pre>
<ul>
<li>First, the lengths are compared. If they are not equal, the arrays are not equal as well.</li>
<li>Then, <code>every()</code> is called on the first array. The callback checks if every element of <code>arr1</code> is equal to the element at the corresponding index in <code>arr2</code>.</li>
</ul>
<pre><code class="lang-js">arr1.every(<span class="hljs-function">(<span class="hljs-params">elem, index</span>) =&gt;</span> elem === arr2[index])
</code></pre>
<p>The AND operator ensures that <code>true</code> is returned only when both conditions are true.</p>
<p>Here's the function applied to the arrays from before:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = [<span class="hljs-number">1</span>, <span class="hljs-literal">null</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> b = [<span class="hljs-number">1</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-number">3</span>];

compareEvery(a,b); <span class="hljs-comment">// false</span>
</code></pre>
<h2 id="heading-how-to-copy-an-array">How to Copy an Array</h2>
<p>All common operations to copy an array in JavaScript generate a <strong><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy">shallow copy</a></strong> – instead of a deep copy – of the original array. This means that by mutating the copy, you can change the original array, too. We will see why this happens in a while.</p>
<h3 id="heading-how-to-use-the-slice-method">How to Use the <code>slice()</code> Method</h3>
<p>The <code>slice()</code> method allows you to copy an entire array – or just a portion of it – without mutating it.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.slice(start, end)
</code></pre>
<p>As parameters, it takes the <strong>starting index</strong> and the <strong>final index</strong> (not included) to copy. When called without arguments, <code>slice()</code> create a duplicate of the whole array. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dough = [<span class="hljs-string">'flour'</span>, <span class="hljs-string">'water'</span>, <span class="hljs-string">'yeast'</span>, <span class="hljs-string">'salt'</span>];

<span class="hljs-keyword">let</span> doughCopy = dough.slice();
<span class="hljs-built_in">console</span>.log(doughCopy); <span class="hljs-comment">// ['flour', 'water', 'yeast', 'salt']</span>
</code></pre>
<p>If you try to change <code>doughCopy</code> in some way, for example, assigning <code>doughCopy[1]</code> a new value, you would see that no change is reflected in the original array:</p>
<pre><code class="lang-js">doughCopy[<span class="hljs-number">1</span>] = <span class="hljs-string">'wine'</span>;
<span class="hljs-built_in">console</span>.log(doughCopy); <span class="hljs-comment">// ['flour', 'wine', 'yeast', 'salt']</span>

<span class="hljs-built_in">console</span>.log(dough); <span class="hljs-comment">// ['flour', 'water', 'yeast', 'salt']</span>
</code></pre>
<p>This happens because the array is filled with primitive values. However, the story is quite different if you handle an array containing non-primitive values.</p>
<p>Let's consider the following array, with two objects:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> albums = [
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'Apostrophe'</span>},
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'One Size Fits All'</span>}
];
</code></pre>
<p>You copy the array using the <code>slice()</code> method, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> albumsCopy = albums.slice();
</code></pre>
<p>Now, <code>albumsCopy</code> represents a shallow copy of <code>albums</code> and the elements inside each array point to the same objects. In other words, both <code>albums[0] === albumsCopy[0]</code> and <code>albums[1] === albumsCopy[1]</code> return <code>true</code> – remember that this comparison involves object references – because they are the very same objects.</p>
<p>If you change one of them by mutating a property value, the modification involves the other array, too.</p>
<pre><code class="lang-js">albumsCopy[<span class="hljs-number">1</span>][<span class="hljs-string">'title'</span>] = <span class="hljs-string">'Absolutely Free'</span>;
<span class="hljs-built_in">console</span>.log(albumsCopy);
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//  {artist: 'Frank Zappa', title: 'Apostrophe'},</span>
<span class="hljs-comment">//  {artist: 'Frank Zappa', title: 'Absolutely Free'}</span>
<span class="hljs-comment">// ];</span>

<span class="hljs-built_in">console</span>.log(albums);
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//  {artist: 'Frank Zappa', title: 'Apostrophe'},</span>
<span class="hljs-comment">//  {artist: 'Frank Zappa', title: 'Absolutely Free'}</span>
<span class="hljs-comment">// ];</span>
</code></pre>
<p>Note that if you reassign an element to a different object – that is without mutating any of the existent objects – the modification does not involve the other array:</p>
<pre><code class="lang-js">albumsCopy[<span class="hljs-number">1</span>] = {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Captain Beefheart'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'Safe as Milk'</span>};

<span class="hljs-built_in">console</span>.log(albumsCopy);
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//  {artist: 'Frank Zappa', title: 'Apostrophe'},</span>
<span class="hljs-comment">//  {artist: 'Captain Beefheart', title: 'Safe as Milk'}</span>
<span class="hljs-comment">// ];</span>

<span class="hljs-built_in">console</span>.log(albums);
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//  {artist: 'Frank Zappa', title: 'Apostrophe'},</span>
<span class="hljs-comment">//  {artist: 'Frank Zappa', title: 'Absolutely Free'}</span>
<span class="hljs-comment">// ];</span>
</code></pre>
<h3 id="heading-how-to-use-the-map-method">How to Use the <code>map()</code> Method</h3>
<p>The <code>map()</code> method generates a new array containing the result of calling a callback function on every element of an array. </p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.map(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {})
</code></pre>
<p>The function takes the current element, its index, and the array on which the method is called, as parameters. </p>
<p>You can use <code>map()</code> to copy an array by specifying a function that returns each array element:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> albums = [
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'Apostrophe'</span>},
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'One Size Fits All'</span>}
];

<span class="hljs-keyword">let</span> mapAlbums = albums.map(<span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> element);
<span class="hljs-built_in">console</span>.log(mapAlbums);
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//  {artist: 'Frank Zappa', title: 'Apostrophe'},</span>
<span class="hljs-comment">//  {artist: 'Frank Zappa', title: 'One Size Fits All'}</span>
<span class="hljs-comment">// ];</span>
</code></pre>
<h3 id="heading-how-to-create-a-deep-copy">How to Create a Deep Copy</h3>
<p>If you want to create a deep clone of an array, you can convert the array into a string with <code>JSON.stringify()</code> and pass its return value to the <code>JSON.parse()</code> method.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> albums = [
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'Apostrophe'</span>},
    {<span class="hljs-attr">artist</span>: <span class="hljs-string">'Frank Zappa'</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'One Size Fits All'</span>}
];

<span class="hljs-keyword">let</span> albumsCopy = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(albums));
<span class="hljs-built_in">console</span>.log(albumsCopy);
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//  {artist: 'Frank Zappa', title: 'Apostrophe'},</span>
<span class="hljs-comment">//  {artist: 'Frank Zappa', title: 'One Size Fits All'}</span>
<span class="hljs-comment">// ];</span>
</code></pre>
<p>In this way, the copy will be completely independent of the original array and you will not risk an unintentional modification.</p>
<h2 id="heading-how-to-search-inside-an-array">How to Search Inside an Array</h2>
<p>Depending on what you are looking for, there are several ways to search inside an array. Let's explore some methods to search inside an array by index and by value.</p>
<h3 id="heading-how-to-use-the-includes-method">How to Use the <code>includes()</code> Method</h3>
<p>If you need to know whether a value is included in an array, you can call the <code>includes()</code> method on it, passing the value you are interested in as the argument.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.includes(value, startingIndex)
</code></pre>
<p>This method returns <code>true</code> if the value is found. Otherwise, <code>false</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dMinor = [<span class="hljs-string">'D'</span>, <span class="hljs-string">'E'</span>, <span class="hljs-string">'F'</span>, <span class="hljs-string">'G'</span>, <span class="hljs-string">'A'</span>, <span class="hljs-string">'B♭'</span>, <span class="hljs-string">'C'</span>];

dMinor.includes(<span class="hljs-string">'E'</span>); <span class="hljs-comment">// true</span>
dMinor.includes(<span class="hljs-string">'E'</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p>It accepts also a second parameter, representing the index where to begin to search – the default is zero.</p>
<h3 id="heading-how-to-use-the-indexof-method">How to Use the <code>indexOf()</code> Method</h3>
<p>If you need to know the index at which a specific value can be found in an array, you should use the <code>indexOf()</code> method.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.indexOf(value, startingIndex)
</code></pre>
<p>It returns only the <strong>first index</strong> at which the specified value is found, otherwise, it returns -1. The second parameter is the index for where to start searching for the value – the default is zero.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dMinor = [<span class="hljs-string">'D'</span>, <span class="hljs-string">'E'</span>, <span class="hljs-string">'F'</span>, <span class="hljs-string">'G'</span>, <span class="hljs-string">'A'</span>, <span class="hljs-string">'B♭'</span>, <span class="hljs-string">'C'</span>];

dMinor.indexOf(<span class="hljs-string">'E'</span>); <span class="hljs-comment">// 1</span>
dMinor.indexOf(<span class="hljs-string">'E'</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// -1</span>
</code></pre>
<h3 id="heading-how-to-use-the-find-amp-findlast-methods">How to Use the <code>find()</code> &amp; <code>findLast()</code> Methods</h3>
<p><code>find()</code> and <code>findLast()</code> enable you to search for the <strong>first</strong> and the <strong>last</strong> element that satisfies a certain condition in an array, respectively.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.find(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {})

array.findLast(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {})
</code></pre>
<p>They both accept a callback function, whose parameters are the current element, its index, and the array the method is called upon.</p>
<p><code>find()</code> and <code>findLast()</code> return the first/last element that satisfies the function, or <code>undefined</code> when the no value matches the specified condition.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [
    {<span class="hljs-attr">no</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part One)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Dogs'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs (Three Different Ones)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">4</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Sheep'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part Two)'</span>}
];

animals.find(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el[<span class="hljs-string">'track'</span>].includes(<span class="hljs-string">'Pigs'</span>));
<span class="hljs-comment">// {no: 1, track: 'Pigs on the Wing (Part One)'}</span>

animals.findLast(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el[<span class="hljs-string">'track'</span>].includes(<span class="hljs-string">'Pigs'</span>));
<span class="hljs-comment">// {no: 5, track: 'Pigs on the Wing (Part Two)'}</span>

animals.find(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el[<span class="hljs-string">'track'</span>].includes(<span class="hljs-string">'Horses'</span>));
<span class="hljs-comment">// undefined</span>
</code></pre>
<p>In the example above, only the first and the last objects containing 'Pigs' are found. The middle object <code>{no: 3, track: 'Pigs (Three Different Ones)'}</code> cannot be reached by these two methods.</p>
<h3 id="heading-how-to-use-the-findindex-amp-findlastindex-methods">How to Use the <code>findIndex()</code> &amp; <code>findLastIndex()</code> Methods</h3>
<p>The <code>findIndex()</code> and <code>findLastIndex()</code> methods work similarly to the previous ones.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.findIndex(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {})

array.findLastIndex(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {})
</code></pre>
<p>But they return the <strong>index</strong> of the first and the last element that satisfies the provided condition, respectively, or <code>undefined</code> when the no value matches the specified condition.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [
    {<span class="hljs-attr">no</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part One)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Dogs'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs (Three Different Ones)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">4</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Sheep'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part Two)'</span>}
];

animals.findIndex(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el[<span class="hljs-string">'track'</span>].includes(<span class="hljs-string">'Pigs'</span>)); <span class="hljs-comment">// 0</span>

animals.findLastIndex(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el[<span class="hljs-string">'track'</span>].includes(<span class="hljs-string">'Pigs'</span>)); <span class="hljs-comment">// 4</span>

animals.findIndex(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el[<span class="hljs-string">'track'</span>].includes(<span class="hljs-string">'Horses'</span>)); <span class="hljs-comment">// -1</span>
</code></pre>
<h2 id="heading-how-to-check-if-array-elements-meet-a-condition">How to Check if Array Elements Meet a Condition</h2>
<h3 id="heading-how-to-use-the-every-amp-some-methods">How to Use the <code>every()</code> &amp; <code>some()</code> Methods</h3>
<p>Sometimes you want to verify if the elements inside an array satisfy a specific condition. We have already seen the <code>every()</code> method in a previous section. It loops through the array and returns <code>true</code> if all the elements meet the specified condition. Otherwise, it returns <code>false</code>.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.every(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {})

array.some(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {})
</code></pre>
<p>The <code>some()</code> method is very similar. It iterates through the array, testing if <strong>some</strong> elements – not all of them – meet the requirements implemented by a callback function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>];

nobleGases.every(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> <span class="hljs-keyword">typeof</span> el == <span class="hljs-string">'string'</span>); <span class="hljs-comment">// true</span>

nobleGases.some(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el == <span class="hljs-string">'Ar'</span>); <span class="hljs-comment">// true</span>

nobleGases.some(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el == <span class="hljs-string">'Rn'</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p>The last call returns <code>false</code> since none of the array elements is equal to the string <code>'Rn'</code>.</p>
<h3 id="heading-how-to-use-the-filter-method">How to Use the <code>filter()</code> Method</h3>
<p>This method provides you a way to filter the array elements that satisfy a certain criterion.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.filter(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {})
</code></pre>
<p><code>filter()</code> takes a callback function, whose parameters are the current element, its index, and the array the method is called upon.</p>
<p>It creates a shallow copy of the original array containing only the values for which the callback returns a truthy value, and it neglects the others.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [
    {<span class="hljs-attr">no</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part One)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Dogs'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs (Three Different Ones)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">4</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Sheep'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part Two)'</span>}
];

animals.filter(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el[<span class="hljs-string">'track'</span>].includes(<span class="hljs-string">'Pigs'</span>));
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// {no: 1, track: 'Pigs on the Wing (Part One)'},</span>
<span class="hljs-comment">// {no: 3, track: 'Pigs (Three Different Ones)'},</span>
<span class="hljs-comment">// {no: 5, track: 'Pigs on the Wing (Part Two)'}</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<p>Above, only the elements including 'Pigs' are inserted in the filtered array.</p>
<h2 id="heading-how-to-sort-an-array">How to Sort an Array</h2>
<h3 id="heading-how-to-use-the-sort-method">How to Use the <code>sort()</code> Method</h3>
<p>If you want to sort an array, you can use <code>sort()</code>. This method sorts the array elements <strong>in place</strong>. It changes the array which it's acting on.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.sort()

array.sort(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {})
</code></pre>
<p>The default sorting procedure evaluates Unicode point values and sometimes may lead to unexpected outcomes. For this reason, it is better to pass <code>sort()</code> a callback function so that the elements can be sorted according to the return value of the callback.</p>
<p>The following table sums up the sorting criterion at the base of <code>sort()</code>.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>(a, b) comparison return value</td><td>order</td></tr>
</thead>
<tbody>
<tr>
<td>&gt; 0</td><td>[b, a]</td></tr>
<tr>
<td>&lt; 0</td><td>[a, b]</td></tr>
<tr>
<td>=== 0</td><td>original order</td></tr>
</tbody>
</table>
</div><p>The elements – represented by a and b parameters – are compared two at a time. If the return value is positive, a is placed after b. If it is negative, b is placed after a. While if the return value is zero the original order is kept.</p>
<p>Here's an example of sorting an array of strings in ascending and descending order:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> nobleGases = [<span class="hljs-string">'He'</span>, <span class="hljs-string">'Ne'</span>, <span class="hljs-string">'Ar'</span>, <span class="hljs-string">'Kr'</span>, <span class="hljs-string">'Xn'</span>, <span class="hljs-string">'Rn'</span>];

<span class="hljs-comment">// sorting in ascending order</span>
nobleGases.sort(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
   <span class="hljs-keyword">return</span> a === b ? <span class="hljs-number">0</span> : a &gt; b ? <span class="hljs-number">1</span> : <span class="hljs-number">-1</span>; 
}); 
<span class="hljs-comment">// ['Ar', 'He', 'Kr', 'Ne', 'Rn', 'Xn']</span>

<span class="hljs-comment">// sorting in descending order</span>
nobleGases.sort(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
   <span class="hljs-keyword">return</span> a === b ? <span class="hljs-number">0</span> : a &lt; b ? <span class="hljs-number">1</span> : <span class="hljs-number">-1</span>; 
});
<span class="hljs-comment">// ['Xn', 'Rn', 'Ne', 'Kr', 'He', 'Ar']</span>
</code></pre>
<p>The callback function is implemented by a ternary operator, in order to consider the three possible outcomes of the comparison.</p>
<h2 id="heading-how-to-perform-an-operation-on-every-array-element">How to Perform an Operation on Every Array Element</h2>
<h3 id="heading-how-to-use-the-map-method-1">How to Use the <code>map()</code> Method</h3>
<p>Previously, we used <code>map()</code> to duplicate an array. But by using a different callback function you can perform many different operations.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [
    {<span class="hljs-attr">no</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part One)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Dogs'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs (Three Different Ones)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">4</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Sheep'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part Two)'</span>}
];

<span class="hljs-keyword">let</span> tracks = animals.map(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el[<span class="hljs-string">'track'</span>]);

<span class="hljs-built_in">console</span>.log(tracks); <span class="hljs-comment">// ['Pigs on the Wing (Part One)', 'Dogs', 'Pigs (Three Different Ones)', 'Sheep', 'Pigs on the Wing (Part Two)']</span>
</code></pre>
<p>In the example above, we have used <code>map()</code> to create an array populated with the values of the <code>track</code> key of each object in the <code>animals</code> array.</p>
<h3 id="heading-how-to-use-the-foreach-method">How to Use the <code>forEach()</code> Method</h3>
<p>The <code>forEach()</code> method is similar to <code>map()</code>. It executes a function on every array element, but it has no return value. For this reason, a <code>forEach()</code> call can be used only at the end of a chain.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.forEach(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {})
</code></pre>
<p>In the example below, <code>forEach()</code> is used to delete the <code>no</code> property from each array element:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [
    {<span class="hljs-attr">no</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part One)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Dogs'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs (Three Different Ones)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">4</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Sheep'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part Two)'</span>}
];

animals.forEach(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> <span class="hljs-keyword">delete</span> el[<span class="hljs-string">'no'</span>]); <span class="hljs-comment">// it returns undefined</span>

<span class="hljs-built_in">console</span>.log(animals); 
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   {track: 'Pigs on the Wing (Part One)'},</span>
<span class="hljs-comment">//   {track: 'Dogs'},</span>
<span class="hljs-comment">//   {track: 'Pigs (Three Different Ones)'},</span>
<span class="hljs-comment">//   {track: 'Sheep'},</span>
<span class="hljs-comment">//   {track: 'Pigs on the Wing (Part Two)'}</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<h3 id="heading-how-to-use-the-reduce-method">How to Use the <code>reduce()</code> Method</h3>
<p>The <code>reduce()</code> method accepts a callback function, which is executed on each array element. The callback takes an accumulator as the first parameter, followed by the current element, its index, and the array which the method is called on.</p>
<p>The return value of each iteration is passed to the next one. So that the array is reduced to a single value. The second parameter of <code>reduce()</code> is the starting value of the <code>accumulator</code>. If not specified, <code>accumulator</code> takes the first array value and the iteration starts at index 1.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Syntax</span>
array.reduce(<span class="hljs-function">(<span class="hljs-params">accumulator, element, index, array</span>) =&gt;</span> {}, initialValue)
</code></pre>
<p>In the example below, the <code>reduce()</code> method is used to count the number of tracks that include 'Pigs' in the title. The method iterates through the array, and when the track property includes 'Pigs', the value of count is incremented and passed to the next iteration.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [
    {<span class="hljs-attr">no</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part One)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Dogs'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs (Three Different Ones)'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">4</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Sheep'</span>},
    {<span class="hljs-attr">no</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">track</span>: <span class="hljs-string">'Pigs on the Wing (Part Two)'</span>}
];

<span class="hljs-keyword">let</span> countPigs = animals.reduce(<span class="hljs-function">(<span class="hljs-params">count, el</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> el[<span class="hljs-string">'track'</span>].includes(<span class="hljs-string">'Pigs'</span>) ? count + <span class="hljs-number">1</span> : count
    }, <span class="hljs-number">0</span>);

<span class="hljs-built_in">console</span>.log(countPigs); <span class="hljs-comment">// 3</span>
</code></pre>
<p>In this case, it's important to specify the initial value as zero. Otherwise, the initial value will be the whole <code>{no: 1, track: 'Pigs on the Wing (Part One)'}</code> object, and this will lead to an unexpected result.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In JavaScript, arrays are data structures that contain multiple values in a specific order. They can hold values of different data types and they are re-sizable.</p>
<p>In this tutorial, we started with the basics of arrays in JavaScript and then we discussed some of the most common methods that allow you to manipulate arrays.</p>
<p>We have only begun to scratch the surface of this wide topic, but I hope this is a good starting point for you.</p>
<p>Thanks for reading, and happy coding.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript String Tutorial – String Methods in JS ]]>
                </title>
                <description>
                    <![CDATA[ A string is a sequence of characters intended to represent text. Strings can contain any kind of character, like letters, numbers, or special characters.  They are a very useful data type and you will be probably working with them frequently. So it's... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-string-tutorial-string-methods-in-js/</link>
                <guid isPermaLink="false">66bb91183e3fa59ecfecb874</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dario Di Cillo ]]>
                </dc:creator>
                <pubDate>Fri, 10 Mar 2023 19:14:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/belen-garrido-n642zkjBAEY-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A string is a sequence of characters intended to represent text. Strings can contain any kind of character, like letters, numbers, or special characters. </p>
<p>They are a very useful data type and you will be probably working with them frequently. So it's important to know how to manipulate them efficiently.</p>
<p>In this article, you will learn about:</p>
<ul>
<li>The basics of strings in JavaScript</li>
<li>Common string methods in JavaScript</li>
</ul>
<p>Let's start.</p>
<h2 id="heading-the-basics-of-strings-in-javascript">The Basics of Strings in JavaScript</h2>
<p>Here's a simple definition of a <a target="_blank" href="https://www.freecodecamp.org/news/what-is-a-string-in-javascript/">string</a>:</p>
<blockquote>
<p>In JavaScript, a string is a data type representing a sequence of characters that may consist of letters, numbers, symbols, words, or sentences.</p>
</blockquote>
<p>Strings are used to represent text. So, basically, anything that is a <a target="_blank" href="https://unicode.org/charts/">Unicode character</a>.</p>
<p>Let's proceed and see something practical.</p>
<h3 id="heading-how-to-create-strings-in-javascript">How to create strings in JavaScript</h3>
<p>In JavaScript, you can create strings by wrapping the text inside single quotes (<code>'</code>), double quotes (<code>"</code>), or backticks (```).</p>
<pre><code class="lang-js"><span class="hljs-comment">// A string created using single quotes</span>
<span class="hljs-keyword">let</span> string1 = <span class="hljs-string">'I am a very cool string! 😎'</span>;

<span class="hljs-comment">// A string created using double quotes</span>
<span class="hljs-keyword">let</span> string2 = <span class="hljs-string">"I am a very cool string! 😎"</span>;

<span class="hljs-comment">// A string created using backticks, also known as template literal</span>
<span class="hljs-keyword">let</span> string3 = <span class="hljs-string">`I am a very cool string! 😎`</span>;
</code></pre>
<p>Strings created in this way, as in the example above, are treated equally. You can easily compare them to prove it:</p>
<pre><code class="lang-js">string1 === string2; <span class="hljs-comment">// true</span>

string1 === string3; <span class="hljs-comment">// true</span>

string2 === string3; <span class="hljs-comment">// true</span>
</code></pre>
<p>Strings created using backticks are also known as <em>template literals</em> and possess special features which we will discuss in a while.</p>
<p>A string created using single quotes, double quotes, or backticks is generated as a <strong>primitive value</strong>, similar to numbers and boolean values. Primitive data are <strong>immutable</strong>, which means they cannot be changed. Also, they do not have any methods or properties.</p>
<p>For your knowledge, there is another way to create strings in JavaScript, which is via the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String"><code>String()</code> constructor</a>. The <code>String()</code> constructor generates a string as an <strong>object</strong> (when called with <code>new</code>). If called as a function (<code>str2</code> in the example below), the value is <a target="_blank" href="https://www.freecodecamp.org/news/coercion-and-type-conversion-in-javascript/">coerced</a> to a primitive string.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> str1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">String</span>(<span class="hljs-string">'What am I?'</span>);
<span class="hljs-keyword">typeof</span> str1; <span class="hljs-comment">// 'object'</span>

<span class="hljs-keyword">let</span> str2 = <span class="hljs-built_in">String</span>(<span class="hljs-string">'What am I?'</span>);
<span class="hljs-keyword">typeof</span> str2; <span class="hljs-comment">// 'string'</span>

<span class="hljs-keyword">let</span> str3 = <span class="hljs-string">"What am I?"</span>;
<span class="hljs-keyword">typeof</span> str3; <span class="hljs-comment">// 'string'</span>

str1 === str2; <span class="hljs-comment">// false</span>
str1 === str3; <span class="hljs-comment">// false</span>
str2 === str3; <span class="hljs-comment">// true</span>
</code></pre>
<p>The <code>typeof</code> operator returns a string indicating the data type of the operand. This time, although <code>str1</code> and <code>str2</code> might seem equal, their comparison returns <code>false</code>, since they are completely different values.</p>
<p>Note: From now on I will discuss exclusively primitive strings.</p>
<h2 id="heading-basic-string-manipulation-in-javascript">Basic String Manipulation in JavaScript</h2>
<h3 id="heading-string-indexing">String indexing</h3>
<p>You can access each character inside a string through its numeric <strong>index</strong> – starting from zero – using bracket notation:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'larch'</span>;
str[<span class="hljs-number">0</span>]; <span class="hljs-comment">// 'l'</span>
str[<span class="hljs-number">1</span>]; <span class="hljs-comment">// 'a'</span>
str[<span class="hljs-number">2</span>]; <span class="hljs-comment">// 'r'</span>
str[<span class="hljs-number">3</span>]; <span class="hljs-comment">// 'c'</span>
str[<span class="hljs-number">4</span>]; <span class="hljs-comment">// 'h'</span>
</code></pre>
<p>Also, you can use the <code>charAt()</code> method to get a specific character inside the string:</p>
<pre><code class="lang-js">str.charAt(<span class="hljs-number">0</span>); <span class="hljs-comment">// 'l'</span>
</code></pre>
<p>While you can use bracket notation to change <em>non-primitive</em> data, for example, arrays:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arr = [<span class="hljs-string">'birch'</span>, <span class="hljs-string">'larch'</span>, <span class="hljs-string">'oak'</span>];
<span class="hljs-keyword">typeof</span> arr; <span class="hljs-comment">// 'object'</span>
arr[<span class="hljs-number">2</span>] = <span class="hljs-string">'scots pine'</span>;
<span class="hljs-built_in">console</span>.log(arr); <span class="hljs-comment">// ['birch', 'larch', 'scots pine']</span>
</code></pre>
<p>You <strong>cannot mutate</strong> a string, since it is a <em>primitive</em> value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'larch'</span>;
<span class="hljs-keyword">typeof</span> str; <span class="hljs-comment">// 'string'</span>
str[<span class="hljs-number">0</span>] = <span class="hljs-string">'m'</span>; <span class="hljs-comment">//This could throw an error if you are in strict mode</span>
<span class="hljs-built_in">console</span>.log(str); <span class="hljs-comment">// 'larch'</span>
</code></pre>
<p>The value of our <code>str</code> variable is still <code>'larch'</code> and you cannot do anything to mutate it. This peculiarity of primitive values does not mean that you can't make the <code>str</code> variable point to a different value through reassignment:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'larch'</span>;
str = <span class="hljs-string">'march'</span>; <span class="hljs-comment">// Reassigning str another value</span>
<span class="hljs-built_in">console</span>.log(str); <span class="hljs-comment">// 'march'</span>
</code></pre>
<p>Just a note – some of the following examples will use lines from these songs:</p>
<ul>
<li><em>Always Look on the Bright Side of Life</em>, lyrics by Eric Idle</li>
<li><em>The Trek</em> by Primus</li>
<li><em>The Trees</em> by Rush</li>
</ul>
<h3 id="heading-the-length-property">The <code>length</code> property</h3>
<p>You get the number of characters contained in a string using the <code>length</code> property:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sentence = <span class="hljs-string">'Always look on the bright side of life'</span>;
sentence.length; <span class="hljs-comment">// 38</span>
</code></pre>
<p>The <code>length</code> property returns the number of characters the string is composed of, including white spaces. So the last character of our sentence will have the index 37 (the value returned by length -1, because indexing starts at 0).</p>
<h3 id="heading-string-concatenation">String concatenation</h3>
<p>You can concatenate (or join) two or more strings using the concatenation operator, <code>+</code>. Check out the following example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = <span class="hljs-string">'When candles are out,'</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-string">'all cats are grey.'</span>;
<span class="hljs-keyword">let</span> c = a + <span class="hljs-string">' '</span> + b;
<span class="hljs-built_in">console</span>.log(c); <span class="hljs-comment">// 'When candles are out, all cats are grey.'</span>
</code></pre>
<p>Note that I added an extra string between <code>a</code> and <code>b</code> to give the final sentence the correct spacing.</p>
<p>You can do a similar thing with the use of the addition assignment operator <code>+=</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = <span class="hljs-string">'When candles are out,'</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-string">'all cats are grey.'</span>;
<span class="hljs-built_in">console</span>.log(a += <span class="hljs-string">' '</span>); <span class="hljs-comment">// 'When candles are out, '</span>
<span class="hljs-built_in">console</span>.log(a += b); <span class="hljs-comment">// 'When candles are out, all cats are grey.'</span>
</code></pre>
<p>By doing that, the <code>a</code> variable is assigned to its value plus the value on the right side of the operator (<code>+=</code>). Now, <code>a</code> holds the entire sentence, while in the previous example the complete sentence was stored in another variable, <code>c</code>.</p>
<p>If you try to concatenate a number to a string, that number will be coerced to a string value. For example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The '</span> + <span class="hljs-number">3</span> + <span class="hljs-string">' Musketeers'</span>); <span class="hljs-comment">// 'The 3 Musketeers'</span>
</code></pre>
<h3 id="heading-string-comparison">String comparison</h3>
<p>You can compare strings based on their alphabetical order and length using arithmetic comparison operators. The return value is a boolean. </p>
<p>In the example below, we are comparing two strings according to their alphabetical order:</p>
<pre><code class="lang-js"><span class="hljs-string">'Berry'</span> &lt; <span class="hljs-string">'Copper'</span>; <span class="hljs-comment">// true</span>
<span class="hljs-comment">// because 'B' comes before 'C'</span>

<span class="hljs-string">'Berry'</span> &lt; <span class="hljs-string">'Bingo'</span>; <span class="hljs-comment">// true</span>
<span class="hljs-comment">// because the first characters are the same and 'e' comes before 'i'</span>

<span class="hljs-string">'berry'</span> &lt; <span class="hljs-string">'Copper'</span>; <span class="hljs-comment">// false</span>
<span class="hljs-comment">// because the comparison is case-sensitive and capital letters come first</span>
</code></pre>
<p>The comparison is performed letter by letter, starting from the first one. And it is actually based on the Unicode order. That's why <em>C</em> comes before <em>b</em> – uppercase letters are placed before lowercase letters inside the Unicode table.</p>
<p>For the same reason, <code>'$' &lt; '&amp;'</code> evaluates <code>true</code> – <em>$</em> comes before <em>&amp;</em> in the Unicode table.</p>
<p>After letter-by-letter comparison, if each character equates its counterpart in the other string, and the strings have the same length, they are equal. Otherwise, the longest string is the greater. </p>
<p>In the example below, <code>quote</code> lacks the final exclamation mark, so <code>quoteMark</code> is greater:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> quote = <span class="hljs-string">'All generalizations are dangerous, even this one'</span>;
<span class="hljs-keyword">let</span> quoteMark = <span class="hljs-string">'All generalizations are dangerous, even this one!'</span>;
quote &lt; quoteMark; <span class="hljs-comment">// true</span>
</code></pre>
<p>If you need to compare the lengths of two strings, you simply use the length property:</p>
<pre><code class="lang-js">quote.length &lt; quoteMark.length; <span class="hljs-comment">// true</span>
</code></pre>
<h3 id="heading-template-literals">Template literals</h3>
<p>Before, we said that template literals (strings created with backticks, ```) have some special features. One is the ability to display the text on multiple lines, easy peasy.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> chorus = <span class="hljs-string">`Don't lose heart, comrades
It's over that hill
Paradise is just over that hill`</span>;

<span class="hljs-built_in">console</span>.log(chorus);
<span class="hljs-comment">//Don't lose heart, comrades</span>
<span class="hljs-comment">//It's over that hill</span>
<span class="hljs-comment">//Paradise is just over that hill</span>
</code></pre>
<p>The displayed text mirrors the spacing used to write the string. That would not have been the case for other literal strings, which require the use of a newline character, <code>\n</code>, in order to have the text arranged in a multi-line fashion. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> verse = <span class="hljs-string">"There is unrest in the forest\nTrouble with the trees"</span>;

<span class="hljs-built_in">console</span>.log(verse);
<span class="hljs-comment">//There is unrest in the forest</span>
<span class="hljs-comment">//Trouble with the trees</span>
</code></pre>
<p>If you want to include a variable inside a string created with single or double quotes, you should make use of concatenation, as seen before.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> dog1 = <span class="hljs-string">'Bach'</span>;
<span class="hljs-keyword">const</span> dog2 = <span class="hljs-string">'Bingo'</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'My two dogs are called '</span> + dog1 + <span class="hljs-string">' and '</span> + dog2 + <span class="hljs-string">'.'</span>);
<span class="hljs-comment">// My two dogs are called Bach and Bingo.</span>
</code></pre>
<p>But template literals provide a feature called <strong><a target="_blank" href="https://www.freecodecamp.org/news/javascript-string-format-how-to-use-string-interpolation-in-js/">string interpolation</a></strong>, that simplifies the readability and makes the code more fluid. </p>
<p>Here's the previous example rewritten with template literals:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> dog1 = <span class="hljs-string">'Bach'</span>;
<span class="hljs-keyword">const</span> dog2 = <span class="hljs-string">'Bingo'</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My two dogs are called <span class="hljs-subst">${dog1}</span> and <span class="hljs-subst">${dog2}</span>.`</span>);
<span class="hljs-comment">// My two dogs are called Bach and Bingo.</span>
</code></pre>
<p>In short, you assemble the string by substituting the content of placeholders, <code>${}</code>, which is added to the text.</p>
<p>In the example above, each placeholder contains a variable, but placeholders can hold any expression whose value will be converted to a string, building the final string.</p>
<h2 id="heading-common-string-methods-in-javascript">Common String Methods in JavaScript</h2>
<p>As we said previously, primitive data does not have methods and properties. Hey, what about the <code>length</code> property we used before? And the <code>charAt()</code> method? And what about this section?!</p>
<p>Primitive data does not have methods or properties, indeed. But when you call a method on a string, or access a property, JavaScript generates a wrapper object under the hood. In the end, methods and properties perform their job on this wrapper object. After the use, the wrapper object is disposed.</p>
<p>So, it turns out we do have something to discuss in this section. Here are some of the most common string methods in JavaScript with examples.</p>
<h3 id="heading-the-concat-method">The <code>concat()</code> method</h3>
<p>The effect of the <code>concat()</code> method is very similar to using the <code>+</code> and <code>+=</code> operators. It concatenates one or more strings passed as arguments to the string on which the method is called, returning the concatenated string.</p>
<p>Let's rewrite the example from the <a class="post-section-overview" href="#heading-string-concatenation">concatenation</a> section:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = <span class="hljs-string">'When candles are out,'</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-string">'all cats are grey.'</span>;
<span class="hljs-keyword">let</span> c = a.concat(<span class="hljs-string">' '</span>, b);
<span class="hljs-built_in">console</span>.log(c); <span class="hljs-comment">// 'When candles are out, all cats are grey.'</span>
</code></pre>
<h3 id="heading-the-tolowercase-amp-touppercase-methods">The <code>toLowerCase()</code> &amp; <code>toUpperCase()</code> methods</h3>
<p>Sometimes, you might need to manipulate the letter case of specific strings to compare them properly, store inputs with a certain uniformity, or for other reasons.</p>
<p>As their names may suggest, <code>toLowerCase()</code> and <code>toUpperCase()</code> convert a string to lowercase and uppercase letters, respectively. These methods don't change the original string.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sentence = <span class="hljs-string">'Always look on the bright side of life'</span>;

<span class="hljs-built_in">console</span>.log(sentence.toLowerCase());
<span class="hljs-comment">// always look on the bright side of life</span>

<span class="hljs-built_in">console</span>.log(sentence.toUpperCase());
<span class="hljs-comment">// ALWAYS LOOK ON THE BRIGHT SIDE OF LIFE</span>
</code></pre>
<h3 id="heading-the-includes-method">The <code>includes()</code> method</h3>
<p>The <code>includes()</code> method checks if a specified string, passed as an argument, is present inside another string. The search is case-sensitive and the return value is a boolean.</p>
<p>Also, you can specify a second argument stating the index at which to start searching for the specified string.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sentence = <span class="hljs-string">'Always look on the bright side of life'</span>;
sentence.includes(<span class="hljs-string">'look up'</span>); <span class="hljs-comment">// false </span>
sentence.includes(<span class="hljs-string">'look on'</span>); <span class="hljs-comment">// true</span>
sentence.includes(<span class="hljs-string">'look on'</span>, <span class="hljs-number">8</span>); <span class="hljs-comment">// false</span>
</code></pre>
<h3 id="heading-the-indexof-methods">The <code>indexOf()</code> methods</h3>
<p>The <code>indexOf()</code> method searches for a substring and returns the first occurrence of the substring inside the calling string. It takes an optional parameter, indicating a specific index to start searching. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sentence = <span class="hljs-string">'Always look on the bright side of life'</span>;

sentence.indexOf(<span class="hljs-string">'l'</span>); <span class="hljs-comment">// 1</span>
sentence.indexOf(<span class="hljs-string">'l'</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 7</span>
sentence.indexOf(<span class="hljs-string">'l'</span>, <span class="hljs-number">8</span>); <span class="hljs-comment">// 34</span>
sentence.indexOf(<span class="hljs-string">'L'</span>); <span class="hljs-comment">// -1</span>
</code></pre>
<p><code>indexOf()</code> returns the index of the first occurrence of the substring. If the substring is not found, it returns <code>-1</code>. Keep in mind that the search is case-sensitive. That's why <code>sentence.indexOf('L')</code> in the example above returns <code>-1</code>.</p>
<h3 id="heading-the-startswith-amp-endswith-methods">The <code>startsWith()</code> &amp; <code>endsWith()</code> methods</h3>
<p>The <code>startsWith()</code> method checks if a string begins with a specific sequence of characters and returns a boolean value. The search is case-sensitive.</p>
<p>The method takes an optional argument indicating the position in which to start searching for the specified string.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dish = <span class="hljs-string">'Lemon curry'</span>;
dish.startsWith(<span class="hljs-string">'Lem'</span>); <span class="hljs-comment">// true</span>
dish.startsWith(<span class="hljs-string">'lem'</span>); <span class="hljs-comment">// false</span>
dish.toLowerCase().startsWith(<span class="hljs-string">'lem'</span>); <span class="hljs-comment">// true</span>
dish.startsWith(<span class="hljs-string">'cu'</span>); <span class="hljs-comment">// false</span>
dish.startsWith(<span class="hljs-string">'cu'</span>, <span class="hljs-number">6</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p>Similarly, the <code>endsWith()</code> method checks if a string ends with a specific sequence of characters, returning a boolean value. Also in this case the search is case-sensitive.</p>
<p>The optional argument indicates the expected end position of the specified substring (the index of the expected final character + 1).</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dish = <span class="hljs-string">'Lemon curry'</span>;
dish.endsWith(<span class="hljs-string">'ry'</span>); <span class="hljs-comment">// true</span>
dish.endsWith(<span class="hljs-string">'on'</span>, <span class="hljs-number">5</span>); <span class="hljs-comment">// true</span>
</code></pre>
<h3 id="heading-the-slice-amp-substring-methods">The <code>slice()</code> &amp; <code>substring()</code> methods</h3>
<p>The <code>slice()</code> and <code>substring()</code> methods pull a portion of a string, returning it as a new string. They do not change the content of the original string.</p>
<p>The first argument passed to each method is the index of the first character to include in the string to extract. The second argument is the index of the first character to exclude. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sentence = <span class="hljs-string">'Always look on the bright side of life'</span>;

sentence.slice(<span class="hljs-number">7</span>); <span class="hljs-comment">// 'look on the bright side of life'</span>
sentence.substring(<span class="hljs-number">7</span>); <span class="hljs-comment">// 'look on the bright side of life'</span>
sentence.slice(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>); <span class="hljs-comment">// 'Always'</span>
sentence.substring(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>); <span class="hljs-comment">// 'Always'</span>
</code></pre>
<p>These two methods are almost identical, except for a few differences. One of them is that if the first index passed to <code>substring()</code> is greater than the second index, the two arguments are exchanged so that a string is still returned. In the same scenario, the <code>slice()</code> method returns an empty string instead:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sentence = <span class="hljs-string">'Always look on the bright side of life'</span>;

sentence.substring(<span class="hljs-number">11</span>, <span class="hljs-number">7</span>); <span class="hljs-comment">// 'look'</span>
sentence.slice(<span class="hljs-number">11</span>, <span class="hljs-number">7</span>); <span class="hljs-comment">// ''</span>
</code></pre>
<h3 id="heading-the-split-method">The <code>split()</code> method</h3>
<p>The <code>split()</code> method takes a separator argument and breaks a string up, according to the occurrence of the separator character inside the string. Then, it returns an array of strings.</p>
<p>It also takes an optional argument, indicating the maximum number of items to put inside the array. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sentence = <span class="hljs-string">'Always look on the bright side of life'</span>;

sentence.split(<span class="hljs-string">' '</span>); <span class="hljs-comment">// ['Always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']</span>
sentence.split(<span class="hljs-string">' '</span>, <span class="hljs-number">5</span>); <span class="hljs-comment">// ['Always', 'look', 'on', 'the', 'bright']</span>
</code></pre>
<h3 id="heading-the-match-method">The <code>match()</code> method</h3>
<p>The <code>match()</code> method searches for a specific pattern – passed as a regular expression – inside a string, and returns an array containing the matching results. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> tongueTwister = <span class="hljs-string">"How much wood would a woodchuck chuck if a woodchuck could chuck wood?"</span>
<span class="hljs-keyword">const</span> regex1 = <span class="hljs-regexp">/(w|c)o*(ul)?d/g</span>;
<span class="hljs-keyword">const</span> regex2 = <span class="hljs-regexp">/wool/g</span>;
tongueTwister.match(regex1);
<span class="hljs-comment">// ['wood', 'would', 'wood', 'wood', 'could', 'wood']</span>
tongueTwister.match(regex2);
<span class="hljs-comment">// null</span>
</code></pre>
<p>If you only need to know if a pattern is present or not inside a string, you should use <code>test()</code>.</p>
<h3 id="heading-the-test-method">The <code>test()</code> method</h3>
<p>The <code>test()</code> method searches for a specific pattern – passed as a regular expression – inside a string, and returns a boolean. The syntax is reversed respective to <code>match()</code>. </p>
<p>Considering the previous example, using the <code>test()</code> method would look like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> tongueTwister = <span class="hljs-string">"How much wood would a woodchuck chuck if a woodchuck could chuck wood?"</span>
<span class="hljs-keyword">const</span> regex1 = <span class="hljs-regexp">/(w|c)o*(ul)?d/g</span>;
<span class="hljs-keyword">const</span> regex2 = <span class="hljs-regexp">/wool/g</span>;
regex1.test(tongueTwister); <span class="hljs-comment">// true</span>
regex2.test(tongueTwister); <span class="hljs-comment">// false</span>
</code></pre>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>A string is a sequence of characters that represents text. In JavaScript, strings are primitive data. You can create them by wrapping the text inside single quotes, double quotes, or backticks.</p>
<p>Template literals enable you to write cleaner code thanks to string interpolation, and when you need multi-line strings.</p>
<p>Strings are everywhere, so you will need to know how to manipulate them efficiently. In this tutorial, you have learned about the most common string methods you will use to work with strings. But there are many more for you to discover!</p>
<p>Happy learning :)</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
