<?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[ object - 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[ object - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 23 Jun 2026 21:16:00 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/object/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Collect.js Tutorial – How to Work with JavaScript Arrays and Objects ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript arrays are one of the most important data structures in the language, since everything is already an object in JavaScript. They're useful in so many applications, and many other data structures build on top of JavaScript arrays and objects... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/work-with-javascript-arrays-objects-with-collect-js/</link>
                <guid isPermaLink="false">66c4c6b6744830ebca763795</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Mon, 08 Jan 2024 22:38:20 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/zub.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript arrays are one of the most important data structures in the language, since everything is already an object in JavaScript.</p>
<p>They're useful in so many applications, and many other data structures build on top of JavaScript arrays and objects. While the language provides a lot of helpful array and object methods, you can take it even a step further using Collect.js.</p>
<p>This article takes you through:</p>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-collectjs">What is Collect.js</a>?</li>
<li><a class="post-section-overview" href="#heading-how-to-install-collectjs">How to install Collect.js</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-collectjs">How to Use Collect.js</a></li>
<li><a class="post-section-overview" href="#heading-some-collectjs-methods">Some Collect.js Methods</a></li>
</ul>
<h2 id="heading-what-is-collectjs">What Is Collect.js?</h2>
<p>The official docs of Collect.js describes it as a "Convenient and dependency free wrapper for working with arrays and objects."</p>
<p>A simpler way to explain this is that Collect.js is a JavaScript library for working with arrays and objects. It provides a layer on top of the built-in functions to make working with them easier.</p>
<p>Collect.js works how <a target="_blank" href="https://laravel.com/docs/10.x/collections">Laravel collections</a> (where the inspiration came from) work. It makes it very easy for Laravel developers, when working with JavaScript, to develop as fast as they would if they were using PHP. But this doesn't mean a native JavaScript developer wouldn't find it really helpful, too.</p>
<p>Collect.js is growing gradually, as it currently has over 6k stars on GitHub and about 200k weekly downloads on NPM at the time of this writing.</p>
<h2 id="heading-how-to-install-collectjs">How to Install Collect.js</h2>
<p>To start using Collect.js in your projects, you have to install it first. Like other JavaScript libraries, you can easily install Collect.js using <code>npm</code> or <code>yarn</code>. You can also install it using a CDN. For this tutorial, we will install it using npm like this:</p>
<pre><code class="lang-bash">npm i collect.js
</code></pre>
<p>After installation, you can import it into the modules where you need it, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> collect <span class="hljs-keyword">from</span> <span class="hljs-string">'collect.js'</span>;
</code></pre>
<p>And once it has been imported, you can begin making magic with Collect.js.</p>
<p>You can read about other installation methods on the <a target="_blank" href="https://collect.js.org/installation.html">official documentation website</a>.</p>
<h2 id="heading-how-to-use-collectjs">How to Use Collect.js</h2>
<p>After installation and importation, to use Collect.js in your projects you'll need to convert your required data to a Collect.js <strong>collection</strong>.</p>
<p>A Collect.js collection is a JavaScript object that has functions not natively available to regular JavaScript arrays and objects. </p>
<p>To create a collection, simply use the <code>collect</code> method imported earlier on any array or object. It's that simple – here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> students = [<span class="hljs-string">'John'</span>, <span class="hljs-string">'James'</span>, <span class="hljs-string">'Ian'</span>, <span class="hljs-string">'David'</span>];

<span class="hljs-keyword">const</span> studentsCollection = collect(students);
</code></pre>
<p>Now, using an IDE like WebStorm, you can see methods available to the simple collection you just created:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-04-at-17.10.21.png" alt="Image" width="600" height="400" loading="lazy">
<em>List of available methods</em></p>
<p>This article does not cover all of these functions, but you can see that you now have more than JavaScript originally offers through Collect.js.</p>
<h2 id="heading-some-collectjs-methods">Some Collect.js Methods</h2>
<p>To help understand how much Collect.js simplifies common array and object methods, we'll now look at how to use some very useful Collect.js methods.</p>
<h3 id="heading-the-average-method-or-avg">The <code>average</code> method (or avg)</h3>
<p>This method, as you may assume, calculates an average of a collection of numbers. Here's how you use it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>];
<span class="hljs-keyword">const</span> average = collect(numbers).avg();

<span class="hljs-built_in">console</span>.log(average); <span class="hljs-comment">// 5.5</span>
</code></pre>
<p>In this example, we've create an array of numbers between 1 and 10, inclusive. Then we get the average of these numbers using Collect.js. </p>
<p>To do this in vanilla JavaScript, you would have to first sum the numbers using <code>array.reduce</code> or a loop, then get the length of the original array, and divide the sum by this length. See the below example implementation:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sum = <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr.reduce( <span class="hljs-function">(<span class="hljs-params"> p, c </span>) =&gt;</span> p + c, <span class="hljs-number">0</span> );
<span class="hljs-keyword">const</span> size = numbers.length;
<span class="hljs-keyword">const</span> average = sum(numbers) / size;

<span class="hljs-built_in">console</span>.log(average); <span class="hljs-comment">// 5.5</span>
</code></pre>
<p>You can see that it's way easier and more elegant using Collect.js.</p>
<p>You can also use the average method directly on more complex structures like an array of objects. Here's an example where the average score of a class of students, stored in an array of students details with a <code>scores</code> key, is calculated using Collect.js:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsDetails = [
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">40</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'James'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">70</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'Ian'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">50</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">60</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span> },
];

<span class="hljs-keyword">const</span> studentsCollection = collect(studentsDetails);
<span class="hljs-keyword">const</span> averageScore = studentsCollection.avg(<span class="hljs-string">'score'</span>);
<span class="hljs-built_in">console</span>.log(averageScore); <span class="hljs-comment">// 55</span>
</code></pre>
<p>Here the average is gotten in a very straightforward approach and takes less effort than doing it in vanilla JavaScript. And it uses the short hand <code>avg</code> instead of the longer <code>average</code>.</p>
<h3 id="heading-the-chunk-method">The <code>chunk</code> method</h3>
<p>This method breaks an array into smaller bits based on a given size. This is a common operation when dealing with JavaScript arrays in real life. A common use case would be in pagination of records.</p>
<p>Using the same <code>studentsDetails</code> array created in the last example, I could break down the collection into groups of two using the <code>chunk</code> method, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsCollection = collect(studentsDetails);
<span class="hljs-keyword">const</span> studentGroups = studentsCollection.chunk(<span class="hljs-number">2</span>);
</code></pre>
<p>This breaks down the original <code>studentsCollection</code> array into two sub collections that look like this:</p>
<pre><code class="lang-js">Collection {
  <span class="hljs-attr">items</span>: [
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">40</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'James'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">70</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span> }
  ]
}
Collection {
  <span class="hljs-attr">items</span>: [
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'Ian'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">50</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">60</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span> }
  ]
}
</code></pre>
<p>To achieve a similar result in vanilla JavaScript takes more effort as you would require a loop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> chunkedArray = [];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; studentsDetails.length; i += <span class="hljs-number">2</span>) {
    <span class="hljs-keyword">const</span> chunk = studentsDetails.slice(i, i + <span class="hljs-number">2</span>);
    chunkedArray.push(chunk);
}

<span class="hljs-built_in">console</span>.log(chunkedArray);
</code></pre>
<h3 id="heading-the-contains-method">The <code>contains</code> method</h3>
<p>You can use this method to check whether some key or value exists in a collection. This function allows you to check regardless of the shape or structure of the data.</p>
<p>For example, to check the existing <code>studentDetails</code> for the subject <code>Physics</code>, you can do this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsDetailsCollection = collect(studentsDetails);

<span class="hljs-built_in">console</span>.log(studentsDetailsCollection.contains(<span class="hljs-string">'Physics'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>To check if we have a student named <code>Science</code> instead of the subject, we could specify what field to check by passing in the field name as a first parameter before the search value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsDetailsCollection = collect(studentsDetails);

<span class="hljs-built_in">console</span>.log(studentsDetailsCollection.contains(<span class="hljs-string">'name'</span>, <span class="hljs-string">'Science'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>You can even check to see if the collection contains values that match a certain condition. Like to see if any student scored more than 50:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsDetailsCollection = collect(studentsDetails);

<span class="hljs-built_in">console</span>.log(studentsDetailsCollection.contains(<span class="hljs-function">(<span class="hljs-params">value, key</span>) =&gt;</span> value.score &gt; <span class="hljs-number">50</span>)); <span class="hljs-comment">// true</span>
</code></pre>
<p>To perform any of these checks in vanilla JavaScript would involve using a loop to check each object in the array. You could also do it using the <code>some</code> method.</p>
<h3 id="heading-the-diff-method">The <code>diff</code> method</h3>
<p>This method is used to get the difference between two collections. The collections could be plain arrays or array of objects. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = collect([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]);
<span class="hljs-keyword">const</span> primeNumbers = collect([<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>]);

<span class="hljs-built_in">console</span>.log(numbers.diff(primeNumbers).all()); <span class="hljs-comment">// [ 1, 4, 6, 8, 9, 10 ]</span>
</code></pre>
<p>Here we get the numbers that are not prime between 1 and 10 inclusive by removing the array of primeNumbers from the array of those numbers using the <code>diff</code> method.</p>
<h3 id="heading-the-get-method">The <code>get</code> method</h3>
<p>This method is used to get values from a collection. If the collection was created from an array, it can accept the array index to return the value at that position. </p>
<p>If the collection was created from an object, it can accept a key and return the value for that key. It returns <code>null</code> when no value is found. You can pass in a default value to prevent it from returning <code>null</code>.</p>
<p>Using the <code>numbers</code> collection created in the last example, you can get the first and twelfth elements, and return 10 if it doesn't exist, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> firstNumber = numbers.get(<span class="hljs-number">0</span>);
<span class="hljs-keyword">const</span> twelfthNumber = numbers.get(<span class="hljs-number">11</span>, <span class="hljs-number">10</span>);

<span class="hljs-built_in">console</span>.log(firstNumber); <span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(twelfthNumber); <span class="hljs-comment">// 10</span>
</code></pre>
<p>The <code>firstNumber</code> returns 1 as expected, but the <code>twelfthNumber</code> returns 10, instead of returning <code>null</code> or throwing an error. This is very useful when dealing with user inputs and having optional parameters.</p>
<h3 id="heading-the-all-method">The <code>all</code> method</h3>
<p>This method has already been used in a few examples, so you can probably guess it's usage already. You use it to get the object or array under the collection.</p>
<p>Using this method on the <code>numbers</code> collection just returns the original array of numbers:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(numbers.all()); <span class="hljs-comment">// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]</span>
</code></pre>
<h3 id="heading-the-groupby-method">The <code>groupBy()</code> method</h3>
<p>If you have any SQL experience, this method name will sound familiar. It works similarly to the SQL function, too: it groups data in a collection by a given key. </p>
<p>Using this method, we can group the students by the subject offered, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsGroupedBySubject = collect(studentsDetails).groupBy(<span class="hljs-string">'subject'</span>);
<span class="hljs-built_in">console</span>.log(studentsGroupedBySubject.all());
</code></pre>
<p>This will create two subcollections for the two subjects, maths and physics.</p>
<pre><code class="lang-js">{
  <span class="hljs-attr">Maths</span>: Collection { <span class="hljs-attr">items</span>: [ [<span class="hljs-built_in">Object</span>], [<span class="hljs-built_in">Object</span>] ] },
  <span class="hljs-attr">Science</span>: Collection { <span class="hljs-attr">items</span>: [ [<span class="hljs-built_in">Object</span>], [<span class="hljs-built_in">Object</span>] ] }
}
</code></pre>
<h3 id="heading-the-isempty-and-isnotempty-methods">The <code>isEmpty</code> and <code>isNotEmpty</code> methods</h3>
<p>The <code>isEmpty</code> method checks is a collection is empty, and the <code>isNotEmpty</code> checks otherwise. These methods help prevent the <a target="_blank" href="https://learn.snyk.io/lesson/prototype-pollution/">object spoofing</a> vulnerability.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(numbers.isEmpty()) <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(numbers.isNotEmpty()) <span class="hljs-comment">// true</span>
</code></pre>
<h3 id="heading-the-first-and-last-methods">The <code>first</code> and <code>last</code> methods</h3>
<p>These method names are as descriptive as they can be. The <code>first</code> method gets the first element of a collection. It can also be used to get the first that matches a condition.</p>
<p>For example, to get the first student that scores more than 40 in the <code>subject</code> maths, you can use the <code>first</code> method like this:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(studentsDetailsCollection.first(<span class="hljs-function">(<span class="hljs-params">student</span>) =&gt;</span> student.score &gt; <span class="hljs-number">40</span> &amp;&amp; student.subject === <span class="hljs-string">'Maths'</span>));
</code></pre>
<p>The <code>last</code> method is also very similar to the <code>first</code> method. It gets the last element of a collection when called with no condition. When a condition is specified, it gets the last element that matches that condition. </p>
<p>For example, to get the last student that fails maths in the <code>studentsDetailsCollection</code>, use this code:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(studentsDetailsCollection.last(<span class="hljs-function">(<span class="hljs-params">student</span>) =&gt;</span> student.score &lt; <span class="hljs-number">40</span> &amp;&amp; student.subject === <span class="hljs-string">'Maths'</span>));
</code></pre>
<p>This last example returns <code>undefined</code> as no student fails maths.</p>
<p>To acheive these same results using vanilla JavaScript would involve a loop that checks each element and keeps track of the first and last that match the condition, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getFirstStudentThatPassesMaths = <span class="hljs-function">(<span class="hljs-params">studentDetails</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> firstStudentThatPassesMaths = <span class="hljs-literal">undefined</span>;

    studentDetails.forEach(<span class="hljs-function">(<span class="hljs-params">student</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (student.subject === <span class="hljs-string">'Maths'</span> &amp;&amp; student.score &gt; <span class="hljs-number">40</span>) {
            firstStudentThatPassesMaths = student;
            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
        }
    });

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

<span class="hljs-keyword">const</span> getLastStudentThatFailsMaths = <span class="hljs-function">(<span class="hljs-params">studentDetails</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> lastStudentThatFailsMaths = <span class="hljs-literal">undefined</span>;

    studentDetails.forEach(<span class="hljs-function">(<span class="hljs-params">student</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (student.subject === <span class="hljs-string">'Maths'</span> &amp;&amp; student.score &lt; <span class="hljs-number">40</span>) {
            lastStudentThatFailsMaths = student;
        }
    });

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

<span class="hljs-built_in">console</span>.log(getFirstStudentThatPassesMaths(studentsDetails));
<span class="hljs-built_in">console</span>.log(getLastStudentThatFailsMaths(studentsDetails));
</code></pre>
<p>See how much simpler the Collect.js implementations are.</p>
<h3 id="heading-the-macro-method">The <code>macro</code> method</h3>
<p>This method is very useful, as it allows you even extend Collect.js further by adding your own methods. It has the following structure:</p>
<pre><code class="lang-js">collect().macro(<span class="hljs-string">'functionName'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// function body</span>
});
</code></pre>
<p>Here, <code>functionName</code> is the name of the new function you're adding, and the function body is where your new logic goes.</p>
<p>For example, to assign grades to students using our <code>studentsDetailsCollection</code>, we can create a new method called <code>grade</code>. We can make it a bit more complex and have the function modify the collection by adding the calculated grade to each student object.</p>
<pre><code class="lang-js">collect().macro(<span class="hljs-string">'grade'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.map(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
        <span class="hljs-keyword">if</span> (item.score &gt;= <span class="hljs-number">70</span>) item.grade = <span class="hljs-string">'A'</span>;
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item.score &gt;= <span class="hljs-number">60</span>) item.grade = <span class="hljs-string">'B'</span>;
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item.score &gt;= <span class="hljs-number">50</span>) item.grade = <span class="hljs-string">'C'</span>;
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item.score &gt;= <span class="hljs-number">45</span>) item.grade = <span class="hljs-string">'D'</span>;
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item.score &gt;= <span class="hljs-number">40</span>) item.grade = <span class="hljs-string">'E'</span>;
        <span class="hljs-keyword">else</span> item.grade = <span class="hljs-string">'F'</span>;

        <span class="hljs-keyword">return</span> item;
    });
});
</code></pre>
<p>You can then call the method on the collection like any other built-in method like this:</p>
<pre><code class="lang-js">studentsDetailsCollection.grade();
</code></pre>
<p>After modification, your collection will look like this:</p>
<pre><code class="lang-js">[
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">40</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span>, <span class="hljs-attr">grade</span>: <span class="hljs-string">'E'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'James'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">70</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span>, <span class="hljs-attr">grade</span>: <span class="hljs-string">'A'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Ian'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">50</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span>, <span class="hljs-attr">grade</span>: <span class="hljs-string">'C'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">60</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span>, <span class="hljs-attr">grade</span>: <span class="hljs-string">'B'</span> }
]
</code></pre>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>I hope you now understand how to simplify your JavaScript development using simple Collect.js functions. This article only covers some of the most useful methods, but there are more available. To learn more, refer to the <a target="_blank" href="https://collect.js.org/api.html">official documentation</a>.</p>
<p>If you have any questions or relevant advice, please get in touch with me.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Variable Data Types Explained ]]>
                </title>
                <description>
                    <![CDATA[ By Deborah Kurata Walking into a hardware store, it's not enough to say: "I need a tool". You need to be specific about the type of tool you need.  Each tool type has its particular purpose: A hammer to drive a nail into wood, a paint brush to paint,... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/variable-data-types-explained/</link>
                <guid isPermaLink="false">66d45e153a8352b6c5a2aa1d</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 07 Mar 2023 16:54:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/data-types-thumbnail2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Deborah Kurata</p>
<p>Walking into a hardware store, it's not enough to say: "I need a tool". You need to be specific about the type of tool you need. </p>
<p>Each tool type has its particular purpose: A hammer to drive a nail into wood, a paint brush to paint, and a wrench tightens or loosens nuts and bolts.</p>
<p>The same goes for the variables we use to hold data in our code. Regardless of the programming language you use, when building a website or app you'll want to use the appropriate type of variable for a particular purpose. We'll look at basic types and more complex types such as arrays (lists) and objects.</p>
<p>You can also watch the associated video here which walks through the key variable data types.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8cTu_RrkiME" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-basic-data-types"><strong>Basic Data Types</strong></h2>
<p>The most common basic data types available in most programming languages include:</p>
<p><strong>numbers</strong>: we use this for any data that is numeric or should be worked with as a number for addition or other math operations. </p>
<p>In some programming languages, there are multiple data types for numbers, depending on whether the number is an integer, decimal, or currency, for example. </p>
<p>If we were building a number guessing game, we would hold the guessed number in a numeric data type, like this:</p>
<pre><code class="lang-code">usersGuess = 3
</code></pre>
<p><strong>string</strong>: we use this for any data that is text. For example, a name or address or message. In most programming languages, strings require quotes. Notice that the text inside of the quotes can include spaces and other special characters.</p>
<pre><code class="lang-code">usersName = "Jack Harkness"
</code></pre>
<p><strong>date</strong>: we use this for data that is a date or time, such as a birthday.</p>
<pre><code class="lang-code">usersBirthday = April 14, 2001
</code></pre>
<p><strong>Boolean</strong>: we use this for data that only has the value <code>true</code> or <code>false</code>. In a number guessing game, the user's guess was either correct or it wasn't. There is no other value.</p>
<pre><code class="lang-code">correctGuess = true
</code></pre>
<p>For programming languages that are considered to be "strongly typed", such as C# and TypeScript, the data type defines the kind of data that can be assigned to that variable. You'll see an error if you try to put the wrong type of data into a variable.</p>
<pre><code class="lang-typescript">pageTitle = <span class="hljs-string">'Pet List'</span>;    <span class="hljs-comment">// Variable is a string.</span>

pageTitle = <span class="hljs-number">42</span>;            <span class="hljs-comment">// Error</span>
                        <span class="hljs-comment">// Can't put a number into a string variable</span>
</code></pre>
<p>With "dynamically typed" languages such as JavaScript and Python, the data type defines the kind of data currently assigned to that variable. That type can change if you put a different type of data into that variable. So the type dynamically changes based on the currently assigned value.</p>
<pre><code class="lang-javascript">pageTitle = <span class="hljs-string">'Pet List'</span>;            <span class="hljs-comment">// Variable type is a string</span>

pageTitle = <span class="hljs-number">42</span>;                    <span class="hljs-comment">// Variable type is now a number</span>
</code></pre>
<h2 id="heading-array-list-data-type"><strong>Array (List) Data Type</strong></h2>
<p>Another important data type in programming is an array, which in some programming languages is called a list.</p>
<p>Let's say we add a feature to our website or app so the user can provide the name of each of their pets. We could hold each name in a separate variable like shown in Figure 1.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/array1.jpg" alt="Pictures of three cats with three variables to hold the name of each cat." width="600" height="400" loading="lazy">
<em>Figure 1. Using separate string variables to hold multiple items.</em></p>
<p>But we'd then have to limit how many pets we could allow based on how many variables we'd defined.</p>
<p>Arrays solve this problem. An <strong>array</strong> is a collection or set of data items. You can think of an array as a list of items.</p>
<p>The data items in an array are often of the same type, so you may have an array of numbers, of strings, or of dates.</p>
<p>In some programming languages, including C#, TypeScript, JavaScript, and Python, arrays are defined with square brackets: [ ] and each value in the array is separated with commas.</p>
<pre><code class="lang-code">petNames = ["Yoyo", "Vanny", "Cali"]
</code></pre>
<p>Here we define an array of strings. Recall that strings must be enclosed in quotation marks. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/array2.jpg" alt="Pictures of three cats with a single array to hold the name of each cat." width="600" height="400" loading="lazy">
<em>Figure 2. Using an array to hold multiple items.</em></p>
<p>With arrays, the user can have an almost limitless number of items, such as names, because we can keep appending to the array.</p>
<pre><code class="lang-code">petNames = ["Yoyo", "Vanny", "Cali", "Ben", "Maki"]
</code></pre>
<h2 id="heading-object-data-type-custom-data-type"><strong>Object Data Type (Custom Data Type)</strong></h2>
<p>What about data that represent things in our application? Things like those shown in Figure 3:</p>
<ul>
<li>A pet</li>
<li>A customer</li>
<li>A product</li>
<li>Or post, and I actually mean a social media post here, but close enough.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/object1.jpg" alt="Four icons representing pet, customer, product, and post" width="600" height="400" loading="lazy">
<em>Figure 3. Custom data type (object) examples.</em></p>
<p>We can hold detailed information about a thing, such as a pet or customer or blog post, in a set of string, number, and date variables. But to keep that set of variables for a particular thing together as one variable, we want a custom data type that describes that thing. </p>
<p>Think of an object as a custom data type that groups a set of related variables for a particular thing.</p>
<p>Let's walk through how to define an object as a custom data type.</p>
<h3 id="heading-step-1-identify-properties-characteristics">Step 1: Identify Properties (Characteristics)</h3>
<p>To define an object data type, we first identify the data we want to hold for the object. These are often characteristics of the object, like a pet's name, type, and age. In programming, we call each of these characteristics a <strong>property</strong> of the object.</p>
<p>Let's look at some examples.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/object2.jpg" alt="Four icons representing pet, customer, product, and post and their characteristics" width="600" height="400" loading="lazy">
<em>Figure 4. Identify the data to store (or hold) for each object.</em></p>
<p>For a customer, the properties might be the customer's name, shipping address, and default payment method. </p>
<p>A product may have a product name, description, and a Boolean value defining whether the product is currently in stock.</p>
<p>And for a blog post, we may want to hold the user's name, the post text, and the date.</p>
<p>Each of these are properties of our object.</p>
<p>At this point, we have the list of properties for the object. We want to hold data for each of these properties.</p>
<h3 id="heading-step-2-assign-a-property-name">Step 2: Assign a Property Name</h3>
<p>Once we have the properties defined, we assign a name to each property as shown in Figure 5. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/object3.jpg" alt="Four icons representing pet, customer, product, and post and their property names" width="600" height="400" loading="lazy">
<em>Figure 5. Define a variable name for each object property.</em></p>
<p>The names follow the conventions for the programming language you are using. In general, property names cannot have spaces or special characters in them. They are often defined using camel case, with the first letter lower case and each additional word capitalized.</p>
<p>Each property also has a basic data type. <code>petName</code>, <code>customerName</code>, <code>productName</code>, and <code>userName</code> are strings. <code>age</code> is a number, <code>inStock</code> is a Boolean value (true or false), and <code>postDate</code> is a date.</p>
<p>We could keep track of separate variables for each of these pet properties and each of these customer properties and each of these post properties. But we'd end up with lots of unorganized variables.</p>
<p>Let's instead group each set of related properties into an object.</p>
<h3 id="heading-step-3-group-the-properties-for-the-object">Step 3: Group the Properties for the Object</h3>
<p>We group the properties of an object together using object literal syntax. This keeps the data for an object together and makes it easier to work with it as a set.</p>
<p>The syntax used to group the properties depends on the programming language you use. In languages such as JavaScript, TypeScript, and C#, object properties are grouped within curly braces ({ }).</p>
<pre><code class="lang-code">pet = {
    petName: "Yoyo",
    petType: "cat",
    age: 11
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/object4.jpg" alt="Four icons representing pet, customer, product, and post and a sample object." width="600" height="400" loading="lazy">
<em>Figure 6. Group the properties for each object</em></p>
<p>For each object, the variable on the left of the equal sign is the object variable and represents a specific pet, customer, product, or post. On the right of the equal sign, inside the curly braces, we list each property name, a colon, and the data (often called a value). We separate properties with a comma.</p>
<p>To say that another way, you can think of an object as a collection of name and value pairs. The name is the property name and the value is the data you want to store for that property. </p>
<p>In Figure 6, we defined a pet object with a specific set of properties, and a value for each property. Same with the customer, and so on.</p>
<h2 id="heading-try-it-yourself">Try It Yourself!</h2>
<p>Let's stop here for a moment and think about objects. What's your favorite hobby? If you built a website or an app to support that hobby, what objects might you define?</p>
<p>Maybe you like to bake, so you'd build a recipe app with your favorite recipes. You work with the data for each recipe using an object with properties such as ingredients, recipe steps, baking temperature, and time.</p>
<p>Or say you like sports. You'd track the data for each player using an object with properties such as name, position, and stats. And you'd track the data for each game using another object with properties such as teams and score.</p>
<p>What objects did you define for your hobby?</p>
<h2 id="heading-wrapping-up"><strong>Wrapping Up</strong></h2>
<p>A variable has a data type such as number, string (for text), date, and Boolean (for true or false).</p>
<p>An array stores a set of data items, often of the same type.</p>
<p>An object represents something in the website or app, like a pet, a customer, or a blog post. The object groups related properties holding the data for the object.</p>
<p>Now that you know all about data types, you can create variables of the appropriate type to hold any data you need for your website or app.</p>
<p>If you are self-taught or new to programming and want more information about general programming concepts, check out this course:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/yO4JaMVMerA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ [object, object] in JavaScript – Meaning in JS ]]>
                </title>
                <description>
                    <![CDATA[ When working with objects in JavaScript, you may have come across the [object, object] output. While this may seem irrelevant, it's not necessarily an error.  [object, object] is the string representation of a JavaScript object data type. You'll unde... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/object-object-in-javascript-meaning-in-js/</link>
                <guid isPermaLink="false">66b0a32cb30dd4d00547bba7</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Mon, 25 Jul 2022 14:30:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/clement-helardot-95YRwf6CNw8-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When working with objects in JavaScript, you may have come across the <code>[object, object]</code> output. While this may seem irrelevant, it's not necessarily an error. </p>
<p><code>[object, object]</code> is the string representation of a JavaScript object data type. You'll understand better as we go further in this article.</p>
<p>There are two main contexts where you'll encounter such an output:</p>
<ul>
<li>When you try display an object using the <code>alert()</code> method (most common). </li>
<li>When you use the <code>toString()</code> method on an object. </li>
</ul>
<p>Let's take a look at some examples. </p>
<h2 id="heading-what-happens-if-you-alert-an-object-in-javascript">What Happens If You Alert an Object in JavaScript?</h2>
<p>In this section, you'll see what happens when you use the <code>alert()</code> method to display an object in JavaScript. Here's the code example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> student = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">school</span>: <span class="hljs-string">"freeCodeCamp"</span>,
};

alert(student)
</code></pre>
<p>In the code above, we created an object called <code>student</code>. After using the <code>alert()</code> method to display the object in the browser, we got the output below: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screenshot--301-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>From the image above, instead of having the object and its properties displayed, <code>[object, object]</code> was displayed. </p>
<p>This happens because when you use the <code>alert()</code> method to display an object in JavaScript, you get the string format displayed. </p>
<p>To fix this, you can use the <code>JSON.stringify()</code> method to change the object into a string that can be popped up in the browser using the <code>alert()</code> method. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> student = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">school</span>: <span class="hljs-string">"freeCodeCamp"</span>,
};

alert(<span class="hljs-built_in">JSON</span>.stringify(student));
</code></pre>
<p>When you run the code above, you should have the object and its properties displayed – similar to the image below. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screenshot--303-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-what-happens-when-you-use-the-tostring-method-on-an-object-in-javascript">What Happens When You Use the <code>toString()</code> Method on an Object in JavaScript?</h2>
<p>The <code>toString()</code> method in JavaScript returns the string format of an object. This section will help you understand what happened under the hood in the last section.</p>
<p>When you use the <code>toString()</code> method on an object in JavaScript, you get the string representation – <code>[object, object]</code> – returned. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> student = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">school</span>: <span class="hljs-string">"freeCodeCamp"</span>,
};

<span class="hljs-built_in">console</span>.log(student.toString());
<span class="hljs-comment">// [object Object]</span>
</code></pre>
<p>As you can see in the code above, we used the <code>toString()</code> method on an object called <code>student</code>: <code>student.toString()</code>. </p>
<p>When we logged this to the console, we got <code>[object, object]</code>. </p>
<p>This effect is exactly what happens when you pop up an object in the browser using the <code>alert()</code> method (as we saw in the last section).</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about the odd looking <code>[object, object]</code> output in JavaScript. </p>
<p>We got to understand that the output is the string representation of an object data type in JavaScript. </p>
<p>You're most likely going to see such an output when you try to display an object in the browser using the <code>alert()</code> method, or when you use the <code>toString()</code> method on an object. </p>
<p>We also went through some code examples and images to demonstrate how you can see <code>[object, object]</code> in JavaScript.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Objects in JavaScript – A Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ If you declare multiple variables to hold different values, this can make your program messy and clunky. For instance, if you need to store three characteristics each for 10 individuals, having 30 variables individually declared can make your program... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/objects-in-javascript-for-beginners/</link>
                <guid isPermaLink="false">66d45e0a47a8245f78752a24</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Damilola Oladele ]]>
                </dc:creator>
                <pubDate>Wed, 20 Jul 2022 17:50:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/shelf4.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you declare multiple variables to hold different values, this can make your program messy and clunky.</p>
<p>For instance, if you need to store three characteristics each for 10 individuals, having 30 variables individually declared can make your program appear less organized.</p>
<p>So you need a way to group values with similar characteristics together to make your code more readable. And in JavaScript, objects work well for this purpose.</p>
<p>Unlike other data types, objects are capable of storing complex values. Because of this, JavaScript relies heavily on them. So it's important that you become familiar with what an object is, how to create one, and how you can use it before going in-depth into learning JavaScript.</p>
<p>This article will introduce you to the basics of objects, object syntax, the different methods of creating objects, how to copy objects and how to iterate over an object.</p>
<p>In order to get the most out of this article, you need to have at least a basic understanding of JavaScript, particularly variables, functions, and data types.</p>
<h2 id="heading-what-are-objects-in-javascript">What Are Objects in JavaScript?</h2>
<p>An object is a data type that can take in collections of key-value pairs.</p>
<p>A major difference between an object and other data types such as strings and numbers in JavaScript is that an objects can store different types of data as its values. On the other hand, primitive data types such as numbers and strings can store only numbers and strings, respectively, as their values.</p>
<p>The key, also known as the property name, is usually a string. If any other data type is used as a property name other than strings, it would be converted into a string.</p>
<p>You can visualize an object as a multi-purpose shelf containing space for your gadgets and ornaments as well as a storage space for books, and files.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/shelf1-2.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A shelf with several items in it</em></p>
<p>The most recognizable feature of an object is the brackets which contain the key-value pair.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> emptyObject = {};
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> emptyObject); <span class="hljs-comment">//'object'</span>
</code></pre>
<p>The contents of an object can consist of variables, functions, or both. Variables found in objects are properties, while functions are methods. Methods allow the objects to use the properties within them to perform some kind of action.</p>
<p>For example, in the sample code below, <strong>object1.user</strong>, <strong>object1.nationality</strong> and <strong>object1.profession</strong> are all properties of <strong>object1</strong> while <strong>object1.myBio()</strong> is a method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> object1 = {
    <span class="hljs-attr">user</span>: <span class="hljs-string">"alex"</span>,
    <span class="hljs-attr">nationality</span>: <span class="hljs-string">"Nigeria"</span>,
    <span class="hljs-attr">profession</span>: <span class="hljs-string">"Software Enginneer"</span>,
    myBio() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.user}</span>. I'm a               <span class="hljs-subst">${<span class="hljs-built_in">this</span>.profession}</span> from <span class="hljs-subst">${<span class="hljs-built_in">this</span>.nationality}</span>`</span>)
    }
}
<span class="hljs-built_in">console</span>.log(object1.user); <span class="hljs-comment">//Alex </span>
<span class="hljs-built_in">console</span>.log(object1.nationality); <span class="hljs-comment">//Nigeria </span>
<span class="hljs-built_in">console</span>.log(object1.profession); <span class="hljs-comment">//Software Engineer </span>
<span class="hljs-built_in">console</span>.log(object1.myBio()); <span class="hljs-comment">//My name is alex. I'm a Software Engineer from Nigeria</span>
</code></pre>
<p>The keys in the sample code above are <strong>user</strong>, <strong>nationality</strong> and <strong>profession</strong> while their values are the string values that come after the colons. Also, notice the use of the <strong>this</strong> keyword. The <strong>this</strong> keyword simply refers to the object itself.</p>
<p>As mentioned earlier in this article, the value of a property can be any data type. In the following sample code, the values are both arrays and objects:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> object2 = { 
        <span class="hljs-attr">users</span>: [<span class="hljs-string">"Alex"</span>, <span class="hljs-string">"James"</span>, <span class="hljs-string">"Mohammed"</span>], 
        <span class="hljs-attr">professions</span>: { 
            <span class="hljs-attr">alex</span>: <span class="hljs-string">"software engineer"</span>, 
            <span class="hljs-attr">james</span>: <span class="hljs-string">"lawyer"</span>, 
            <span class="hljs-attr">mohammed</span>: <span class="hljs-string">"technical writer"</span> 
        } 
    }; 
    <span class="hljs-built_in">console</span>.log(object2.users); <span class="hljs-comment">//['Alex', 'James', 'Mohammed'] </span>
    <span class="hljs-built_in">console</span>.log(object2.professions); <span class="hljs-comment">//{alex: 'software engineer', james: 'lawyer', mohammed: 'technical writer'}</span>
</code></pre>
<h2 id="heading-how-to-access-objects-and-create-new-object-properties-or-methods-in-javascript">How to Access Objects and Create New Object Properties or Methods in JavaScript</h2>
<p>There are two ways to access objects: dot notation and bracket notation. In the previous sample code, we used dot notation to access the properties and methods in <strong>object1</strong> and <strong>object2</strong>.</p>
<p>Also, to create new properties and methods after the declaration of an object, you can use either dot notation or bracket notation. You just have to state the new property and give it a value.</p>
<p>For instance, we can add new properties to <strong>object2</strong> like this:</p>
<pre><code class="lang-javascript">object2.ages = [<span class="hljs-number">30</span>, <span class="hljs-number">32</span>, <span class="hljs-number">40</span>];
object2[<span class="hljs-string">"summary"</span>] = <span class="hljs-string">`Object2 has <span class="hljs-subst">${object2.users.length}</span> users`</span>;
<span class="hljs-built_in">console</span>.log(object2);
<span class="hljs-comment">/*
{
    "users": [
        "Alex",
        "James",
        "Mohammed"
    ],
    "professions": {
        "alex": "software engineer",
        "james": "lawyer",
        "mohammed": "technical writer"
    },
    "ages": [
        30,
        32,
        40
    ],
    "summary": "Object2 has 3 users"
}
*/</span>
</code></pre>
<p>Similarly, you can use either notation to change the value of an object:</p>
<pre><code class="lang-javascript">object2.users = [<span class="hljs-string">"jane"</span>, <span class="hljs-string">"Williams"</span>, <span class="hljs-string">"John"</span>];
object2[<span class="hljs-string">"age"</span>] = [<span class="hljs-number">20</span>, <span class="hljs-number">25</span>, <span class="hljs-number">29</span>]
<span class="hljs-built_in">console</span>.log(object2.users); <span class="hljs-comment">//['jane', 'Williams', 'John']</span>
<span class="hljs-built_in">console</span>.log(object2.ages) <span class="hljs-comment">//[20, 25, 29</span>
</code></pre>
<p>Although dot notation is the most commonly used to access an object's properties and methods, it has some limitations. Let's look at them now.</p>
<h3 id="heading-you-cant-use-values-as-property-names-with-dot-notation">You Can't Use Values as Property Names with Dot Notation</h3>
<p>If you want to use the value of a variable as a property name in your object, you have to use bracket notation and not dot notation. Whether the variable value is defined at runtime or not is irrelevant.</p>
<p>Runtime is a phase of a computer program in which the program is run or executed on a computer system.</p>
<p>For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> object3 = {};
<span class="hljs-keyword">const</span> gadget = prompt(<span class="hljs-string">"enter a gadget type"</span>); 
object3[gadget] = [<span class="hljs-string">"jbl"</span>, <span class="hljs-string">"sony"</span>]; 
<span class="hljs-built_in">console</span>.log(object3) <span class="hljs-comment">//(respose entered in prompt): ["jbl","sony"] notice that the property name is the value you enter in the reply to the prompt message</span>
</code></pre>
<p>If you define the variable value in your code, and you use dot notation to set that value as a property name of your object, dot notation will create a new property with the variable name instead of with the variable value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> computer = <span class="hljs-string">"brands"</span>
object3.computer = [<span class="hljs-string">"hp"</span>, <span class="hljs-string">"dell"</span>, <span class="hljs-string">"apple"</span>]
<span class="hljs-built_in">console</span>.log(object3.brands); <span class="hljs-comment">//undefined</span>
<span class="hljs-built_in">console</span>.log(object3.computer)<span class="hljs-comment">//['hp', 'dell', 'apple']</span>

object3[computer] = [<span class="hljs-string">"hp"</span>, <span class="hljs-string">"dell"</span>, <span class="hljs-string">"apple"</span>]
<span class="hljs-built_in">console</span>.log(object3.brands) <span class="hljs-comment">//['hp', 'dell', 'apple']</span>
</code></pre>
<p>Notice the omission of quotes within the square brackets. This is because the brackets took in a variable.</p>
<h3 id="heading-you-cant-use-multi-word-properties-with-dot-notation">You Can't Use Multi-Word Properties with Dot Notation</h3>
<p>Where the property name is a multi-word string then dot notation is insufficient. For instance:</p>
<pre><code class="lang-javascript">object3.users height = [<span class="hljs-number">5.6</span>, <span class="hljs-number">5.4</span>, <span class="hljs-number">6.0</span>];
Console.log(object3.users height); <span class="hljs-comment">//SyntaxError</span>
</code></pre>
<p>A syntax error occurs because JavaScript reads the command as <code>object3.users</code>, but the string height is not recognized so it returns a syntax error.</p>
<p>When using dot notation to access objects, the usual rules of declaring a variable apply. This means that if you want to use dot notation to access an object or create a property, the property name must not start with a number, must not include any spaces, and can only include the special characters <em>$</em> and _<em>.</em></p>
<p>To avoid this kind of error, you have to use bracket notation. For instance, you can correct the above sample code like this:</p>
<pre><code class="lang-javascript">object3[<span class="hljs-string">"users height"</span>] = [<span class="hljs-number">5.6</span>, <span class="hljs-number">5.4</span>, <span class="hljs-number">6.0</span>];  
<span class="hljs-built_in">console</span>.log(object3[<span class="hljs-string">"users height"</span>]); <span class="hljs-comment">//[5.6, 5.4, 6]</span>
</code></pre>
<h2 id="heading-how-to-create-objects-with-the-object-constructor-in-javascript">How to Create Objects with the Object Constructor in JavaScript</h2>
<p>There are two methods by which you can create an object: an object literal and the object constructor. The objects used so far as samples in this article are object literals. Object literals work well if you want to create a single object.</p>
<p>But if you want to create more than one object, it is always better to use the object constructor. This allows you to avoid unnecessary repetition in your code and also makes it easier to change the properties of your object.</p>
<p>Basically, constructors are functions whose names are usually capitalized. The capitalization of a constructor name does not have any effect on the object. It is only a means of identification.</p>
<p>You can use a constructor to create a new object by calling the constructor with the <strong>new</strong> keyword. The <strong>new</strong> keyword will create an instance of an object and bind the <strong>this</strong> keyword to the new object.</p>
<p>As earlier mentioned in this article, the <strong>this</strong> keyword is a reference to the object itself.</p>
<p>An example of an object constructor is:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Profile</span>(<span class="hljs-params">name, age, nationality</span>) </span>{ 
    <span class="hljs-built_in">this</span>.name = name; 
    <span class="hljs-built_in">this</span>.age = age; 
    <span class="hljs-built_in">this</span>.nationality = nationality; 
    <span class="hljs-built_in">this</span>.bio = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ 
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>. I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old. I'm from <span class="hljs-subst">${<span class="hljs-built_in">this</span>.nationality}</span>`</span>) 
    } 
};

<span class="hljs-keyword">const</span> oladele = <span class="hljs-keyword">new</span> Profile(<span class="hljs-string">"Oladele"</span>, <span class="hljs-number">50</span>, <span class="hljs-string">"Nigeria"</span> );
<span class="hljs-built_in">console</span>.log(oladele.bio()); <span class="hljs-comment">//My name is Oladele. I'm 50 years old. I'm from Nigeria</span>
</code></pre>
<h2 id="heading-how-to-create-object-copies-in-javascript">How to Create Object Copies in JavaScript</h2>
<p>Unlike primitive data types such as strings and numbers, assigning an existing object to another variable will not produce a copy of the original but rather a reference in memory.</p>
<p>What this means is that both the original object and subsequent objects created by assigning the original object as a value are referencing the same item in memory.</p>
<p>This means that a change in the value of any of the objects will also cause a change in the others. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">let</span> y = x;
x = <span class="hljs-number">20</span>;
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">//20</span>
<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">//10</span>

<span class="hljs-keyword">let</span> object4 = { 
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Alex"</span>, 
    <span class="hljs-attr">age</span>: <span class="hljs-number">40</span> 
}; 
<span class="hljs-keyword">let</span> object5 = object4; 
<span class="hljs-built_in">console</span>.log(object5); <span class="hljs-comment">//{name: 'Alex', age: 40} </span>
object4.name = <span class="hljs-string">"Jane"</span>; 
<span class="hljs-built_in">console</span>.log(object5); <span class="hljs-comment">//{name: 'Jane', age: 40}</span>
<span class="hljs-built_in">console</span>.log(object4 === object5); <span class="hljs-comment">//true</span>
</code></pre>
<p>To create a copy of an object, you can use the spread operator.</p>
<h3 id="heading-what-is-the-spread-operator">What is the Spread Operator?</h3>
<p>The spread operator is represented by three dots <code>...</code> . You can use the spread operator to copy the values of any iterable including objects.</p>
<p>An iterable is an object which can be looped over or iterated over with the help of a for...loop. Examples of iterables include objects, arrays, sets, strings, and so on.</p>
<p>To use the spread operator, you will have to prefix it to the object you want to copy from. For instance:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> object6 = {...object5}; 
object5.name = <span class="hljs-string">"Willaims"</span>; 
<span class="hljs-built_in">console</span>.log(object5); <span class="hljs-comment">//{name: 'Willaims', age: 40}</span>
<span class="hljs-built_in">console</span>.log(object6); <span class="hljs-comment">//{name: 'Jane', age: 40}</span>
<span class="hljs-built_in">console</span>.log(object5 === object6); <span class="hljs-comment">//false</span>
</code></pre>
<p>As you can see, unlike in the previous code sample, where a change in the <strong>object4</strong> caused a change in <strong>object5</strong>, the change in <strong>object6</strong> did not result in a change in <strong>object5</strong>.</p>
<h3 id="heading-how-to-use-the-objectassign-method">How to Use the Object.assign() Method</h3>
<p>The <strong>Object.assign()</strong> method copies all enumerable properties of one object into another and then returns the modified object.</p>
<p>The method takes in two parameters. The first parameter is the target object which takes in the properties copied. The second parameter is the source object which has the properties you want to copy. For instance :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> object7  = <span class="hljs-built_in">Object</span>.assign({}, object6); 
<span class="hljs-built_in">console</span>.log(object7); <span class="hljs-comment">//{name: 'Jane', age: 40}</span>
<span class="hljs-built_in">console</span>.log(object7); <span class="hljs-comment">//{name: 'Jane', age: 40}</span>

<span class="hljs-built_in">console</span>.log(object6 === object7); <span class="hljs-comment">//false</span>
object6.age = <span class="hljs-number">60</span>
<span class="hljs-built_in">console</span>.log(object6); <span class="hljs-comment">//{name: 'Jane', age: 60}</span>
<span class="hljs-built_in">console</span>.log(object7); <span class="hljs-comment">//{name: 'Jane', age: 40</span>
</code></pre>
<p>You can see from the above sample code that a change in the value of the <strong>age</strong> property of <strong>object6</strong> did not cause a change in the vale of the <strong>age</strong> property of <strong>object7</strong>.</p>
<p>Note that both the spread operator and the <strong>Object.assign()</strong> method can only make a shallow copy of an object.</p>
<p>This means that if you have deeply nested objects or arrays in your source object, only the references to such objects are copied into the target object. So a change in the value of any of the deeply nested objects would cause a change in the value of the deeply nested object of the other. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> objectX = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Mary'</span>, 
    <span class="hljs-attr">age</span>: <span class="hljs-number">40</span>,
    <span class="hljs-attr">gadgets</span>: { 
        <span class="hljs-attr">brand</span>: [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"sony"</span>]
    }
};

<span class="hljs-keyword">let</span> objectY = {...objectX};
objectY.name = <span class="hljs-string">"Bianca"</span>;
objectY.gadgets.brand[<span class="hljs-number">0</span>] = <span class="hljs-string">"hp"</span>;
<span class="hljs-built_in">console</span>.log(objectX);
<span class="hljs-comment">/*
{
    "name": "Mary",
    "age": 40,
    "gadgets": {
        "brand": [
            "hp",
            "sony"
        ]
    }
}
*/</span> 

<span class="hljs-built_in">console</span>.log(objectY);
<span class="hljs-comment">/*
{
    "name": "Bianca",
    "age": 40,
    "gadgets": {
        "brand": [
            "hp",
            "sony"
        ]
    }
}
*/</span>
</code></pre>
<p>The above sample code performed the following actions:</p>
<ol>
<li><p>Created an object named <strong>objectX</strong>.</p>
</li>
<li><p>Gave three properties to <strong>objectX</strong>: name, age and gadgets.</p>
</li>
<li><p>Gave the <strong>gadgets</strong> property of <strong>objectX</strong> an object as its value.</p>
</li>
<li><p>Gave the object value of the <strong>gadget</strong> property a <strong>brand</strong> property.</p>
</li>
<li><p>Gave the <strong>brand</strong> property an array as its value.</p>
</li>
<li><p>Copied the properties in <strong>objectX</strong> into <strong>objectY</strong> with the use of the spread operator.</p>
</li>
<li><p>Changed the value of the <strong>name</strong> property of <strong>objectY</strong> to <strong>Mary</strong>.</p>
</li>
<li><p>Changed the the first item in the array value of the <strong>brand</strong> property from <strong>apple</strong> to <strong>hp</strong>.</p>
</li>
</ol>
<p>In the sample code, the array value is a deeply nested object. Notice that a change in the value of the <strong>name</strong> property of <strong>objectY</strong> did not cause a change in the value of the <strong>name</strong> property of <strong>objectX</strong>. But a change in the deeply nested object of <strong>objectY</strong> caused a similar change in the deeply nested object of <strong>objectX</strong> .</p>
<h2 id="heading-how-to-iterate-over-objects-in-javascript">How to Iterate Over Objects in JavaScript</h2>
<p>Use a <strong>for...in</strong> loop to iterate over an object and to select its properties. The <strong>for..in</strong> loop syntax is as follows:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> key <span class="hljs-keyword">in</span> object) {
    <span class="hljs-comment">//perform action(s) for each key</span>
}
</code></pre>
<p>The <strong>key</strong> keyword in the syntax above is a parameter for the properties. So you can replace it with any word of your choice. Replace the object keyword with the name of the object you want to iterate over. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> objectZ = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Ade"</span>,
    <span class="hljs-attr">Pronuon</span>: <span class="hljs-string">"he"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">60</span>
};
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> property <span class="hljs-keyword">in</span> objectZ) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${property}</span>: <span class="hljs-subst">${objectZ[property]}</span>`</span>)
}
<span class="hljs-comment">/* 
name: Ade
Pronuon: he
age: 60
*/</span>
</code></pre>
<p>Notice the use of bracket notation in the loop to get the values of the property. Using dot notation instead of bracket notation would return undefined.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In JavaScript, objects are probably the most important data type. Programming concepts like Object-Oriented programming work on the principle of leveraging the flexibility of objects to store complex values and their distinct capability of interacting with properties and methods within the object.</p>
<p>This article lays a solid foundation for understanding such advanced concepts by explaining the basics of objects.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Loop Through an Object in JavaScript – How to Iterate Over an Object in JS ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, when you hear the term "loop", you probably think of using the various loop methods like for loops, forEach(), map() and others. But in the case of objects, unfortunately, these methods don't work because objects are not iterable. This... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-iterate-over-objects-in-javascript/</link>
                <guid isPermaLink="false">66d45fa79f2bec37e2da0632</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Wed, 20 Jul 2022 15:55:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/cover-template--2-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, when you hear the term "loop", you probably think of using the various loop methods like <a target="_blank" href="https://www.freecodecamp.org/news/javascript-for-loops/"><code>for</code> loops</a>, <a target="_blank" href="https://www.freecodecamp.org/news/javascript-foreach-js-array-for-each-example/"><code>forEach()</code></a>, <code>map()</code> and others.</p>
<p>But in the case of objects, unfortunately, these methods don't work because objects are not iterable.</p>
<p>This doesn't mean we can't loop through an object – but this means that we can't loop through an object directly the same way we do for an array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arr = [<span class="hljs-number">24</span>, <span class="hljs-number">33</span>, <span class="hljs-number">77</span>];
arr.forEach(<span class="hljs-function">(<span class="hljs-params">val</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(val)); <span class="hljs-comment">// ✅✅✅</span>

<span class="hljs-keyword">for</span> (val <span class="hljs-keyword">of</span> arr) {
  <span class="hljs-built_in">console</span>.log(val); <span class="hljs-comment">// ✅✅✅</span>
}

<span class="hljs-keyword">let</span> obj = { <span class="hljs-attr">age</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span> };
obj.forEach(<span class="hljs-function">(<span class="hljs-params">val</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(val)); <span class="hljs-comment">// ❌❌❌</span>

<span class="hljs-keyword">for</span> (val <span class="hljs-keyword">of</span> obj) {
  <span class="hljs-built_in">console</span>.log(val); <span class="hljs-comment">// ❌❌❌</span>
}
</code></pre>
<p>In this article, You'll learn how you can loop through an object in JavaScript. There are two methods you can use - and one of them pre-dates the introduction of ES6.</p>
<h2 id="heading-how-to-loop-through-an-object-in-javascript-with-a-forin-loop">How to loop through an object in JavaScript with a <code>for…in</code> loop</h2>
<p>Before ES6, we relied on the <code>for...in</code> method whenever we wanted to loop through an object.</p>
<p>The <code>for...in</code> loop iterates through properties in the prototype chain. This means that we need to check if the property belongs to the object using <code>hasOwnProperty</code> whenever we loop through an object with the <code>for…in</code> loop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> population = {
  <span class="hljs-attr">male</span>: <span class="hljs-number">4</span>,
  <span class="hljs-attr">female</span>: <span class="hljs-number">93</span>,
  <span class="hljs-attr">others</span>: <span class="hljs-number">10</span>
};

<span class="hljs-comment">// Iterate through the object</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">in</span> population) {
  <span class="hljs-keyword">if</span> (population.hasOwnProperty(key)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${key}</span>: <span class="hljs-subst">${population[key]}</span>`</span>);
  }
}
</code></pre>
<p>To avoid the stress and difficulty of looping and to use the <code>hasOwnProperty</code> method, ES6 and ES8 introduced object static methods. These convert object properties to arrays, allowing us to use array methods directly.</p>
<h2 id="heading-how-to-loop-through-an-object-in-javascript-with-object-static-methods">How to loop through an object in JavaScript with object static methods</h2>
<p>An object is made up of properties that have key-value pairs, that is each property always has a corresponding value.</p>
<p>Object static methods let us extract either <code>keys()</code>, <code>values()</code>, or both keys and values as <code>entries()</code> in an array, allowing us to have as much flexibility over them as we do with actual arrays.</p>
<p>We have three object static methods, which are:</p>
<ul>
<li><p><code>Object.keys()</code></p>
</li>
<li><p><code>Object.values()</code></p>
</li>
<li><p><code>Object.entries()</code></p>
</li>
</ul>
<h3 id="heading-how-to-loop-through-an-object-in-javascript-with-the-objectkeys-method">How to loop through an object in JavaScript with the <code>Object.keys()</code> method</h3>
<p>The <code>Object.keys()</code> method was introduced in ES6. It takes the object we want to loop over as an argument and returns an array containing all property names (also known as keys).</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> population = {
  <span class="hljs-attr">male</span>: <span class="hljs-number">4</span>,
  <span class="hljs-attr">female</span>: <span class="hljs-number">93</span>,
  <span class="hljs-attr">others</span>: <span class="hljs-number">10</span>
};

<span class="hljs-keyword">let</span> genders = <span class="hljs-built_in">Object</span>.keys(population);

<span class="hljs-built_in">console</span>.log(genders); <span class="hljs-comment">// ["male","female","others"]</span>
</code></pre>
<p>This now gives us the advantage of applying any array looping method to iterate through the array and retrieve the value of each property:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> genders = <span class="hljs-built_in">Object</span>.keys(population);

genders.forEach(<span class="hljs-function">(<span class="hljs-params">gender</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(gender));
</code></pre>
<p>This will return:</p>
<pre><code class="lang-bash"><span class="hljs-string">"male"</span>
<span class="hljs-string">"female"</span>
<span class="hljs-string">"others"</span>
</code></pre>
<p>We can also use the key to get the value using bracket notation such as <code>population[gender]</code> as seen below:</p>
<pre><code class="lang-js">genders.forEach(<span class="hljs-function">(<span class="hljs-params">gender</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`There are <span class="hljs-subst">${population[gender]}</span> <span class="hljs-subst">${gender}</span>`</span>);
})
</code></pre>
<p>This will return:</p>
<pre><code class="lang-bash"><span class="hljs-string">"There are 4 male"</span>
<span class="hljs-string">"There are 93 female"</span>
<span class="hljs-string">"There are 10 others"</span>
</code></pre>
<p>Before we move on, let's use this method to sum all the population by looping through so we know the total population:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> population = {
  <span class="hljs-attr">male</span>: <span class="hljs-number">4</span>,
  <span class="hljs-attr">female</span>: <span class="hljs-number">93</span>,
  <span class="hljs-attr">others</span>: <span class="hljs-number">10</span>
};

<span class="hljs-keyword">let</span> totalPopulation = <span class="hljs-number">0</span>;
<span class="hljs-keyword">let</span> genders = <span class="hljs-built_in">Object</span>.keys(population);

genders.forEach(<span class="hljs-function">(<span class="hljs-params">gender</span>) =&gt;</span> {
  totalPopulation += population[gender];
});

<span class="hljs-built_in">console</span>.log(totalPopulation); <span class="hljs-comment">// 107</span>
</code></pre>
<h3 id="heading-how-to-loop-through-an-object-in-javascript-with-the-objectvalues-method">How to loop through an object in JavaScript with the <code>Object.values()</code> method</h3>
<p>The <code>Object.values()</code> method is very similar to the <code>Object.keys()</code> method and was introduced in ES8. This method takes the Object we want to loop over as an argument and returns an array containing all key values.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> population = {
  <span class="hljs-attr">male</span>: <span class="hljs-number">4</span>,
  <span class="hljs-attr">female</span>: <span class="hljs-number">93</span>,
  <span class="hljs-attr">others</span>: <span class="hljs-number">10</span>
};

<span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">Object</span>.values(population);

<span class="hljs-built_in">console</span>.log(numbers); <span class="hljs-comment">// [4,93,10]</span>
</code></pre>
<p>This now gives us the advantage of applying any array looping method to iterate through the array and retrieve the <code>value</code> of each property:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">Object</span>.values(population);

numbers.forEach(<span class="hljs-function">(<span class="hljs-params">number</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(number));
</code></pre>
<p>This will return:</p>
<pre><code class="lang-bash">4
93
10
</code></pre>
<p>We can efficiently perform the total calculation since we can loop through directly:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> totalPopulation = <span class="hljs-number">0</span>;
<span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">Object</span>.values(population);

numbers.forEach(<span class="hljs-function">(<span class="hljs-params">number</span>) =&gt;</span> {
  totalPopulation += number;
});

<span class="hljs-built_in">console</span>.log(totalPopulation); <span class="hljs-comment">// 107</span>
</code></pre>
<h3 id="heading-how-to-loop-through-an-object-in-javascript-with-the-objectentries-method">How to loop through an object in JavaScript with the Object.entries() method</h3>
<p>The <code>Object.entries()</code> method was also introduced with ES8. In the basic sense, what it does is that it outputs an array of arrays, whereby each inner array has two elements which are the property and the value.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> population = {
  <span class="hljs-attr">male</span>: <span class="hljs-number">4</span>,
  <span class="hljs-attr">female</span>: <span class="hljs-number">93</span>,
  <span class="hljs-attr">others</span>: <span class="hljs-number">10</span>
};

<span class="hljs-keyword">let</span> populationArr = <span class="hljs-built_in">Object</span>.entries(population);

<span class="hljs-built_in">console</span>.log(populationArr);
</code></pre>
<p>This outputs:</p>
<pre><code class="lang-bash">[
  [<span class="hljs-string">'male'</span>, 4]
  [<span class="hljs-string">'female'</span>, 93]
  [<span class="hljs-string">'others'</span>, 10]
]
</code></pre>
<p>This returns an array of arrays, with each inner array having the <code>[key, value]</code>. You can use any array method to loop through:</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (array <span class="hljs-keyword">of</span> populationArr){
  <span class="hljs-built_in">console</span>.log(array);
}

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// ['male', 4]</span>
<span class="hljs-comment">// ['female', 93]</span>
<span class="hljs-comment">// ['others', 10]</span>
</code></pre>
<p>We could decide to <a target="_blank" href="https://www.freecodecamp.org/news/destructuring-patterns-javascript-arrays-and-objects/">destructure the array</a>, so we get the <code>key</code> and value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> ([key, value] <span class="hljs-keyword">of</span> populationArr){
  <span class="hljs-built_in">console</span>.log(key);
}
</code></pre>
<p>You can learn more about how to <a target="_blank" href="https://www.freecodecamp.org/news/how-to-loop-through-an-array-in-javascript-js-iterate-tutorial/">loop through arrays in this article</a>.</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>In this tutorial, you learned that the best way to loop through an object is to use any object static method based on your needs to first convert to an array before looping.</p>
<p>Have fun coding!</p>
<p>Embark on a journey of learning! <a target="_blank" href="https://joelolawanle.com/contents">Browse 200+ expert articles on web development</a>. Check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content from me.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Prototypes and Inheritance – and Why They Say Everything in JS is an Object ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this short article we're going to talk about prototypal inheritance in JavaScript, and what are the implications of it. Table of Contents Intro How to access a prototype’s properties and methods in JavaScript The prototype chain A... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/prototypes-and-inheritance-in-javascript/</link>
                <guid isPermaLink="false">66d45f1b3dce891ac3a967fe</guid>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Tue, 03 May 2022 16:05:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/pexels-maor-attias-5192478.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this short article we're going to talk about <strong>prototypal inheritance</strong> in JavaScript, and what are the implications of it.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-intro">Intro</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-access-a-prototypes-properties-and-methods-in-javascript">How to access a prototype’s properties and methods in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-prototype-chain">The prototype chain</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-prototype-based-language">A prototype-based language</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-javascript-classes">Javascript classes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-roundup">Roundup</a></p>
</li>
</ul>
<h1 id="heading-intro">Intro</h1>
<p>Have you ever wondered how strings, arrays or objects “know” the methods each of them have? How does a string know it can <code>.toUpperCase()</code> or an array know that it can <code>.sort()</code>? We never defined these methods manually, right?</p>
<p>The answer is that these methods come built-in within each type of data structure thanks to something called <strong>prototype inheritance</strong>.</p>
<p>In JavaScript, an object can inherit properties of another object. The object from where the properties are inherited is called the prototype. In short, objects can inherit properties from other objects — the prototypes.</p>
<p>You’re probably wondering: why the need for inheritance in the first place? Well, inheritance solves the problem of data and logic duplication. By inheriting, objects can share properties and methods without the need of manually setting those properties and methods on each object.</p>
<h2 id="heading-how-to-access-a-prototypes-properties-and-methods-in-javascript"><strong>How to</strong> A<strong>ccess</strong> a P<strong>rototype’s</strong> P<strong>roperties and</strong> M<strong>ethods</strong> in JavaScript</h2>
<p>When we try to access a property of an object, the property is not only searched in the object itself. It's also searched in the prototype of the object, in the prototype of the prototype, and so on – until a property is found that matches the name or the end of the <strong>prototype chain</strong> is reached.</p>
<p>If the property or method isn’t found anywhere in the prototype chain, only then will JavaScript return <code>undefined</code>.</p>
<p>Every object in JavaScript has an internal property called <code>[[Prototype]]</code>.</p>
<p>If we create an array and log it to the console like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
<span class="hljs-built_in">console</span>.log(arr)
</code></pre>
<p>We will see this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/image.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The double square brackets that enclose <code>[[Prototype]]</code> signify that it is an internal property, and cannot be accessed directly in code.</p>
<p>To find the <code>[[Prototype]]</code> of an object, we will use the <code>Object.getPrototypeOf()</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(arr))
</code></pre>
<p>The output will consist of several built-in properties and methods:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/image-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Keep in mind that prototypes can also be changed and modified through different methods.</p>
<h2 id="heading-the-prototype-chain"><strong>The</strong> P<strong>rototype</strong> C<strong>hain</strong></h2>
<p>At the end of the prototype chain is <code>Object.prototype</code>. All objects inherit the properties and methods of <code>Object</code>. Any attempt to search beyond the end of the chain results in <code>null</code>.</p>
<p>If you look for the prototype of the prototype of an array, a function, or a string, you’ll see it’s an object. And that’s because in JavaScript all objects are descendants or instances of <code>Object.prototype</code>, which is an object that sets properties and methods to all other JavaScript data types.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
<span class="hljs-keyword">const</span> arrProto = <span class="hljs-built_in">Object</span>.getPrototypeOf(arr)
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(arrProto))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/image-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Each type of prototype (for example array prototype) defines its own methods and properties, and in some cases overrides the <code>Object.prototype</code> methods and properties (that’s why arrays have methods that objects don’t).</p>
<p>But under the hood and going up the ladder of the prototype chain, <strong>everything in JavaScript is built upon the</strong> <code>Object.prototype</code>.</p>
<p>If we try to look into the prototype of <code>Object.prototype</code> we get <code>null</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
<span class="hljs-keyword">const</span> arrProto = <span class="hljs-built_in">Object</span>.getPrototypeOf(arr)
<span class="hljs-keyword">const</span> objectProto = <span class="hljs-built_in">Object</span>.getPrototypeOf(arrProto)
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(objectProto))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/image-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-a-prototype-based-language"><strong>A Prototype-Based Language</strong></h2>
<p>JavaScript is a <strong>prototype-based language</strong>, meaning object properties and methods can be shared through generalized objects that have the ability to be cloned and extended.</p>
<p>When it comes to inheritance, JavaScript has only one structure: objects.</p>
<p>Each object has a private property (referred to as its <code>[[Prototype]]</code>) that maintains a link to another object called its prototype. That prototype object has its own prototype, and so on until an object whose prototype is <code>null</code> is reached.</p>
<p>By definition, <code>null</code> has no prototype, and acts as the final link in this chain of prototypes.</p>
<p>This is known as prototypical inheritance and differs from class inheritance. Among popular object-oriented programming languages, JavaScript is relatively unique, as other prominent languages such as PHP, Python, and Java are class-based languages, which instead define classes as blueprints for objects.</p>
<p>At this point you may be thinking "But we CAN implement classes on JavaScript!". And yes, we can, but as syntactic sugar. 🤫🤔</p>
<h2 id="heading-javascript-classes">Javascript Classes</h2>
<p>Classes are a way to set a blueprint to create objects with predefined properties and methods. By creating a class with specific properties and methods, you can later on instantiate objects from that class, that will inherit all the properties and methods that that class has.</p>
<p>In JavaScript, we can create classes in the following way:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Alien</span> </span>{
    <span class="hljs-keyword">constructor</span> (name, phrase) {
        <span class="hljs-built_in">this</span>.name = name
        <span class="hljs-built_in">this</span>.phrase = phrase
        <span class="hljs-built_in">this</span>.species = <span class="hljs-string">"alien"</span>
    }
    fly = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Zzzzzziiiiiinnnnnggggg!!"</span>)
    sayPhrase = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.phrase)
}
</code></pre>
<p>And then we can instantiate an object from that class like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> alien1 = <span class="hljs-keyword">new</span> Alien(<span class="hljs-string">"Ali"</span>, <span class="hljs-string">"I'm Ali the alien!"</span>)
<span class="hljs-built_in">console</span>.log(alien1.name) <span class="hljs-comment">// output: "Ali"</span>
</code></pre>
<p>Classes are used as a way to make code more modular, organized, and understandable and are heavily used in OOP programming.</p>
<p>But keep in mind that JavaScript doesn’t really support classes like other languages. The <code>class</code> keyword was introduced with ES6 as syntactic sugar that facilitates this way of organizing code.</p>
<p>To visualize this, see that the same thing we did by previously defining a <code>class</code>, we can do it by defining a function and editing the prototype in the following way:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Alien</span>(<span class="hljs-params">name, phrase</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name
    <span class="hljs-built_in">this</span>.phrase = phrase
    <span class="hljs-built_in">this</span>.species = <span class="hljs-string">"alien"</span>
}

Alien.prototype.fly = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Zzzzzziiiiiinnnnnggggg!!"</span>)
Alien.prototype.sayPhrase = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.phrase)

<span class="hljs-keyword">const</span> alien1 = <span class="hljs-keyword">new</span> Alien(<span class="hljs-string">"Ali"</span>, <span class="hljs-string">"I'm Ali the alien!"</span>)

<span class="hljs-built_in">console</span>.log(alien1.name) <span class="hljs-comment">// output "Ali"</span>
<span class="hljs-built_in">console</span>.log(alien1.phrase) <span class="hljs-comment">// output "I'm Ali the alien!"</span>
alien1.fly() <span class="hljs-comment">// output "Zzzzzziiiiiinnnnnggggg"</span>
</code></pre>
<p>Any function can be invoked as a constructor with the keyword <code>new</code> and the prototype property of that function is used for the object to inherit methods from. In JavaScript, “class” is only used conceptually to describe the above practice – technically they’re just functions.😑</p>
<p>Although this doesn't necessarily make a lot of difference (we can still perfectly implement OOP and use classes like in most other programming languages), it's important to remember that JavaScript is built with prototype inheritance at its core.</p>
<h1 id="heading-roundup">Roundup</h1>
<p>That's it, everyone! As always, I hope you enjoyed the article and learned something new. If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>.</p>
<p>Cheers and see you in the next one! =D</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/AntiqueAthleticGuineapig-size_restricted.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Immutability – Frozen Objects in JS Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, we use an Object to store multiple values as a complex data structure. You create an object with a pair of curly braces {}.  An object can have one or more properties. Each of the properties is a key-value pair separated by a colon(:).... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-immutability-frozen-objects-with-examples/</link>
                <guid isPermaLink="false">66bdfff5cab9472fe774186d</guid>
                
                    <category>
                        <![CDATA[ immutability ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tapas Adhikary ]]>
                </dc:creator>
                <pubDate>Tue, 27 Jul 2021 15:49:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/07/freeCodeCamp-Cover-5.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, we use an <code>Object</code> to store multiple values as a complex data structure. You create an object with a pair of curly braces <code>{}</code>. </p>
<p>An object can have one or more properties. Each of the properties is a key-value pair separated by a <code>colon(:)</code>. The key must be a string or JavaScript symbol type. The value can be of any type, including another object.</p>
<p>With that explanation of an object, let's create one to see how it works:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {
 <span class="hljs-string">'name'</span>: <span class="hljs-string">'Bob'</span>,
 <span class="hljs-string">'age'</span>: <span class="hljs-number">27</span>   
}
</code></pre>
<p>Here we have created an object with two properties (name, age) and their respective values. We have created a variable called <code>user</code> with the <code>const</code> keyword and we've assigned the object to it as a value.</p>
<p>By default, objects are <code>mutable</code>. This means once they're created, you can add a new property to them, modify the value of an existing property, or delete a property.</p>
<p>In my early years of programming, I found the terms <code>mutable</code> and <code>immutable</code> very confusing. Let me try explaining it in simple English. </p>
<p>Mutable is something you can change. Immutable is just the opposite of that. So, <code>mutability</code> is the ability to change over time. <code>Immutability</code> means something is unchanging over time.</p>
<p>There could be situations where you may not want an object to change programmatically. Therefore you'll want to make it immutable. </p>
<p>When an object is immutable, you can't add a new property to it, modify it, or delete an existing property. There is no way even to extend it. </p>
<p>This is what a <code>Frozen Object</code> is, which we'll learn about, practice with, and understand in this article.</p>
<p>I discussed frozen objects in a Twitter thread recently. Please feel free to have a look. This article will expand on the thread with more details and examples.</p>
<div class="embed-wrapper">
        <blockquote class="twitter-tweet">
          <a href="https://twitter.com/tapasadhikary/status/1416995389169971200"></a>
        </blockquote>
        <script defer="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></div>
<h1 id="heading-how-to-create-a-frozen-object-in-javascript">How to Create a Frozen Object in JavaScript</h1>
<p>You can freeze (make immutable) an object using the function <code>Object.freeze(obj)</code>. The object passed to the <code>freeze</code> method will become immutable. The <code>freeze()</code> method also returns the same object.</p>
<p>Let's create an object of supported languages:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> supportedLanguages = {
  <span class="hljs-string">'af'</span>: <span class="hljs-string">'Afrikaans'</span>,
  <span class="hljs-string">'bn'</span>: <span class="hljs-string">'Bengali'</span>,
  <span class="hljs-string">'de'</span>: <span class="hljs-string">'German'</span>,
  <span class="hljs-string">'en'</span>: <span class="hljs-string">'English'</span>,
  <span class="hljs-string">'fr'</span>: <span class="hljs-string">'French'</span>
}
</code></pre>
<p>If you don't want this object to change after it is created, just use the <code>freeze</code> method to make it immutable.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> frozenSupportedLanguages = <span class="hljs-built_in">Object</span>.freeze(supportedLanguages);

<span class="hljs-comment">// The supportedLanguages and frozenSupportedLanguages are same</span>

frozenSupportedLanguages === supportedLanguages; <span class="hljs-comment">// returns true</span>
</code></pre>
<p>Now let's try changing either of the objects and see what happens:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Add a new property</span>
supportedLanguages[<span class="hljs-string">'kn'</span>] = <span class="hljs-string">'Kannada'</span>;

<span class="hljs-comment">// Modify an existing property</span>
supportedLanguages[<span class="hljs-string">"af"</span>] = <span class="hljs-string">'something else'</span>;

<span class="hljs-comment">// Delete a property</span>
<span class="hljs-keyword">delete</span> supportedLanguages.bn; <span class="hljs-comment">// returns false</span>

<span class="hljs-comment">// log the object to the console</span>
<span class="hljs-built_in">console</span>.log(supportedLanguages); <span class="hljs-comment">// Unchanged =&gt; {af: "Afrikaans", bn: "Bengali", en: "English", fr: "French"}</span>
</code></pre>
<p>You'll get errors when you try changing a frozen object (immutable object) in the JavaScript <code>strict</code> environment.</p>
<h1 id="heading-hold-on-doesnt-the-const-keyword-do-the-same-thing">Hold On – doesn't the <code>const</code> keyword do the same thing?</h1>
<p>Ah, not quite. The <code>const</code> keyword and <code>Object.freeze()</code> are not the same things. When you assign an object to a variable created with the const keyword, you can not reassign another value. However, you can modify the assigned objects in whatever way you want.</p>
<p>Let's understand the difference with an example. This time, we will take the same <code>supportedLanguages</code> object but will not freeze it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> supportedLanguages = {
  <span class="hljs-string">'af'</span>: <span class="hljs-string">'Afrikaans'</span>,
  <span class="hljs-string">'bn'</span>: <span class="hljs-string">'Bengali'</span>,
  <span class="hljs-string">'de'</span>: <span class="hljs-string">'German'</span>,
  <span class="hljs-string">'en'</span>: <span class="hljs-string">'English'</span>,
  <span class="hljs-string">'fr'</span>: <span class="hljs-string">'French'</span>
}
</code></pre>
<p>Now you can modify it like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Add a new property</span>
supportedLanguages[<span class="hljs-string">'kn'</span>] = <span class="hljs-string">'Kannada'</span>;

<span class="hljs-comment">// Modify an existing property</span>
supportedLanguages[<span class="hljs-string">"af"</span>] = <span class="hljs-string">'something else'</span>;

<span class="hljs-comment">// Delete a property</span>
<span class="hljs-keyword">delete</span> supportedLanguages.bn; <span class="hljs-comment">// returns true</span>

<span class="hljs-comment">// log the object to the console</span>
<span class="hljs-built_in">console</span>.log(supportedLanguages);
</code></pre>
<p>Now the <code>supportedLanguages</code> object is changed to the following:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-78.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>So, this change is allowed. But if you try to assign a new object to the <code>supportedLanguages</code> variable:</p>
<pre><code class="lang-js">supportedLanguages = {<span class="hljs-string">'id'</span>: <span class="hljs-string">'Indonesian'</span>};
</code></pre>
<p>You will get this error:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-79.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I hope the difference is clear now – it's also a frequently asked interview question.</p>
<h1 id="heading-why-do-we-need-frozen-objects-in-javascript">Why Do We Need Frozen Objects in JavaScript?</h1>
<p>Again, we need frozen objects when we need immutability. In object-oriented programming, it is common to have APIs that we can not extend or modify outside the current context. </p>
<p>Do you remember the <code>final</code> keyword in Java? Or how in the Kotlin programming language, lists are immutable by default? Trying to mutate them at run time causes errors. Immutability is an essential concept to use in functional programming.</p>
<p>Immutability is often important in the JavaScript programming language as well. You may want a configuration object to be immutable, a fixed set of supported language for your applications, or anything else that you don't want to change at the run time.</p>
<h1 id="heading-you-can-freeze-an-array-too">You Can Freeze an Array, Too</h1>
<p>In JavaScript, <code>Arrays</code> are objects under the hood. So you can also apply <code>Object.freeze()</code>to arrays to make them immutable.</p>
<p>Let's take an array of human senses:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> senses = [<span class="hljs-string">'touch'</span>, <span class="hljs-string">'sight'</span>, <span class="hljs-string">'hearing'</span>, <span class="hljs-string">'smell'</span>, <span class="hljs-string">'taste'</span>];
</code></pre>
<p>We can now make it immutable like this:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Object</span>.freeze(senses);
</code></pre>
<p>Now, try to push an element to that array. It's not possible.</p>
<pre><code class="lang-js">senses.push(<span class="hljs-string">'walking'</span>);
</code></pre>
<p>The output will be the following error:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-80.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Try to remove an element from the array:</p>
<pre><code class="lang-js">senses.pop();
</code></pre>
<p>You'll get this error:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-81.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Please notice the error in both the cases. It clearly says, the add and delete property is not allowed as the underlying object is not extensible.</p>
<h1 id="heading-object-freeze-is-shallow">Object Freeze is Shallow</h1>
<p>A JavaScript object property can have another object as its value. It can go to a deeper level down. </p>
<p>When we freeze an object, it is a <code>shallow</code> freeze. This means that only the top-level properties are frozen. If any of the property's values are another object, that inner object is not frozen. You can still make changes to it.</p>
<p>Let's understand this with the example of a configuration object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> config = {
  <span class="hljs-string">'db'</span>: <span class="hljs-string">'postgresql'</span>,
  <span class="hljs-string">'host'</span>: <span class="hljs-string">'acme-ind.com'</span>,
  <span class="hljs-string">'password'</span>: <span class="hljs-string">'fake-password'</span>,
  <span class="hljs-string">'port'</span>: <span class="hljs-number">512</span>,
  <span class="hljs-string">'admin'</span>: {
    <span class="hljs-string">'name'</span>: <span class="hljs-string">'Tapas'</span>,
    <span class="hljs-string">'rights'</span>: [<span class="hljs-string">'create'</span>, <span class="hljs-string">'update'</span>, <span class="hljs-string">'delete'</span>]
  }
}
</code></pre>
<p>The config object has properties like db, host, password, and port with simple string types values. However, the admin property has an object as the value. Now, let's freeze the config object.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Object</span>.freeze(config);
</code></pre>
<p>Now, let's try to change the db name.</p>
<pre><code class="lang-js">config.db = <span class="hljs-string">'redis'</span>;
</code></pre>
<p>It is not allowed as the object is frozen. However, you can do this:</p>
<pre><code class="lang-js">config.admin.name = <span class="hljs-string">'atapas'</span>;
</code></pre>
<p>Here we have changed the property of the nested object. As the object freezing is shallow in nature, it is not going to stop us from changing the nested object. So, if you log the object in the console, this is what you'll get:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-82.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h1 id="heading-how-to-deep-freeze-an-object-in-javascript">How to Deep Freeze an Object in JavaScript</h1>
<p>But how do you deep freeze an object if you need or want to? You may want to freeze all the properties of the object to the deepest level possible, right? We can do that using recursion.</p>
<p>In programming, recursion is a methodology that uses a procedure, function, or algorithm to call itself. <a target="_blank" href="https://www.freecodecamp.org/news/understanding-recursion-in-programming/">Check out this article</a> for an in-depth understanding.</p>
<p>So, we can iterate through every property and recursively apply the freeze method to everything. It will make sure that the nested objects are also frozen. </p>
<p>To do that, you can write a simple function like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> deepFreeze = <span class="hljs-function"><span class="hljs-params">obj</span> =&gt;</span> {
  <span class="hljs-built_in">Object</span>.keys(obj).forEach(<span class="hljs-function"><span class="hljs-params">prop</span> =&gt;</span> {
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> obj[prop] === <span class="hljs-string">'object'</span>) deepFreeze(obj[prop]);
  });
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Object</span>.freeze(obj);
};

deepFreeze(config);
</code></pre>
<h1 id="heading-whats-the-diffecrence-between-freeze-seal-and-preventextentions">What's the Diffecrence Between freeze(), seal(), and preventExtentions()?</h1>
<p>With Object.freeze we achieve full immutability. But there are two other methods that provide object immutability, only partially.</p>
<ul>
<li><code>Object.seal</code> – We can not add a new property or delete existing properties of an object sealed with this method. But we can still update the value of existing properties.</li>
<li><code>Object.preventExtensions</code> – This method prevents new property creation. But you can update and delete existing properties.</li>
</ul>
<p>Here is a table to compare them:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td>Create</td><td>Read</td><td>Update</td><td>Delete</td></tr>
</thead>
<tbody>
<tr>
<td>freeze</td><td>❌</td><td>✔️</td><td>❌</td><td>❌</td></tr>
<tr>
<td>seal</td><td>❌</td><td>✔️</td><td>✔️</td><td>❌</td></tr>
<tr>
<td>preventExtensions</td><td>❌</td><td>✔️</td><td>✔️</td><td>✔️</td></tr>
</tbody>
</table>
</div><h1 id="heading-how-to-unfreeze-a-frozen-object">How to UnFreeze a Frozen Object</h1>
<p>There is no straightforward ways to unfreeze a frozen object in JavaScript. </p>
<p>You can probably simulate an unfreeze by making a copy of the object maintaining the prototype. </p>
<p><a target="_blank" href="https://www.npmjs.com/package/object-unfreeze">Here is an NPM</a> package that does the same with a shallow copy.</p>
<h1 id="heading-in-summary">In Summary</h1>
<p>To Summarize,</p>
<ul>
<li>We can freeze an object to make it immutable.</li>
<li>You use the method <code>Object.freeze</code> to freeze an object.</li>
<li>You can not create a new property, modify or delete an existing property, or extend the object when a freeze is applied.</li>
<li>Declaring a variable with the <code>const</code> keyword with an object value is not same as freezing the object.</li>
<li>You can freeze an array using the same <code>freeze</code> method.</li>
<li>The freeze method does a shallow freeze. Use recursion to do a deep freeze.</li>
<li>The <code>seal()</code> and <code>preventExtentions()</code> methods provide partial immutability.</li>
<li>Unfreezing is not supported in the language (yet).</li>
</ul>
<h1 id="heading-before-we-end">Before We End...</h1>
<p>That's all for now. I hope you've found this article insightful, and that it helps you understand object immutability more clearly.</p>
<p>Let's connect. You will find me active on <a target="_blank" href="https://twitter.com/tapasadhikary">Twitter (@tapasadhikary)</a>. Feel free to give a follow. I've also started sharing knowledge using my <a target="_blank" href="https://youtube.com/c/TapasAdhikary?sub_confirmation=1">YouTube channel</a>, so you can check it out, too.</p>
<p>You may also like these articles:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/the-javascript-array-handbook/">The JavaScript Array Handbook – JS Array Methods Explained with Examples</a></li>
<li><a target="_blank" href="https://blog.greenroots.info/a-practical-guide-to-object-destructuring-in-javascript">A practical guide to object destructuring in JavaScript</a></li>
<li><a target="_blank" href="https://blog.greenroots.info/javascript-equality-comparison-with-and-objectis">JavaScript: Equality comparison with ==, === and Object.is</a></li>
<li><a target="_blank" href="https://blog.greenroots.info/how-not-to-use-git-in-practice-ten-git-usages-you-should-know-to-avoid">How NOT to use Git in Practice. Ten Git usages, you should know to avoid.</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a JavaScript Object? Key Value Pairs and Dot Notation Explained ]]>
                </title>
                <description>
                    <![CDATA[ By Danny Thompson Objects are one of the most valuable things you can learn in JavaScript. You can use them to take your programs to the next level.  An object is a collection of data – or key value pairs – which consist of variables and functions th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-javascript-object/</link>
                <guid isPermaLink="false">66d45e013a8352b6c5a2aa0d</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 07 Jul 2021 22:04:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/07/Blue--Violet-and-Orange-Shapes-Fitness-Influencer-YouTube-Thumbnail-Set--2--1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Danny Thompson</p>
<p>Objects are one of the most valuable things you can learn in JavaScript. You can use them to take your programs to the next level. </p>
<p>An <strong>object</strong> is a collection of data – or key value pairs – which consist of variables and functions that you can access using dot notation.</p>
<p>Now that's a bunch of words that might not mean anything to you at the moment, so let's break it down. </p>
<h2 id="heading-what-is-a-key-value-pair-in-javascript">What is a Key Value Pair in JavaScript?</h2>
<p>The easiest way to explain a key value pair is that you have 2 items that are linked together. One being the "key" and one being the "value". An object can have several Key Value Pairs inside of it. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/Blue--Violet-and-Orange-Shapes-Fitness-Influencer-YouTube-Thumbnail-Set--3-.png" alt="An image of an object showing the relation between key and value." width="600" height="400" loading="lazy"></p>
<p>Now that we understand what key value pairs are, we can dive deeper into objects.</p>
<h2 id="heading-what-is-an-object-in-javascript">What is an Object in JavaScript?</h2>
<p>This is an object in JavaScript: </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> phone = {
    <span class="hljs-attr">brand</span>: [<span class="hljs-string">'Samsung'</span>, <span class="hljs-string">'Apple'</span>, <span class="hljs-string">'Google'</span>],
    <span class="hljs-attr">quantity</span>: [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>],
    <span class="hljs-attr">howManyGooglePhones</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        alert(<span class="hljs-string">"There are "</span> + <span class="hljs-built_in">this</span>.quantity[<span class="hljs-number">1</span>] + <span class="hljs-string">' '</span> + <span class="hljs-built_in">this</span>.brand[<span class="hljs-number">2</span>] + <span class="hljs-string">" phones available."</span>);
    }
}

phone.howManyGooglePhones();
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-35.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We create and name our object – in this case we have named it <code>phone</code>. We also have everything wrapped in our curly braces { }. Each key is separated from the value using a colon <code>:</code>.</p>
<p>In the code above, we have 2 arrays and one function. Notice how each key value pair ends with a comma <code>,</code> – this is very important and is required.</p>
<h2 id="heading-what-is-dot-notation-in-javascript">What is Dot Notation in JavaScript?</h2>
<p>Dot notation is where we can call that key value pair (which is known as a property) and pulls that information. </p>
<p>If I wanted the brand Samsung I could do <strong><code>phone.brand[0]</code></strong> and it would give me Samsung. We use the object name (in this example it is <code>phone</code>), use a Dot, and then proceed by writing the name of the property.</p>
<p>Our function is set up to display how many phones we have of each brand. In the above function we are using it to show how many Google Phones we have in stock.</p>
<p><strong><code>this.quantity[1]</code></strong> is accessing the "quantity" property and is looking in the [1] position for the value. <strong><code>this.brand[2]</code></strong> is accessing the Brand property that we want to show, which in this case is Google. </p>
<p>Can you quickly figure out how we would access Apple with the quantity being 3? What would that look like in this situation?</p>
<p><code>this</code> is being used because we want to access these values from within this object. The alert is creating a pop up to display this info when the program loads for this example.</p>
<p>Now that our object is complete, we want to call the function that is in the object and have it displayed. Since we are no longer in the object, <strong>we will not be using <code>this</code></strong> like we did inside of the object. </p>
<p><strong>Instead</strong> we will be calling the object by name and using Dot notation. Our object name is <strong><code>phone</code></strong> so let's use it then the name of the function:</p>
<p><strong><code>phone.howManyGooglePhones();</code></strong></p>
<p>Calling the function will now create this pop up:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-34.png" alt="Pop up alert shows that there are 2 Google Phones available." width="600" height="400" loading="lazy"></p>
<p>You successfully went through making an object, called a function, that was in the object that accessed 2 different values from the properties. Nice work!</p>
<p>If you like my blog articles you will love my social media posts.<br>Follow me on Twitter @DThompsonDev</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Mutable vs Immutable Objects in Python – A Visual and Hands-On Guide ]]>
                </title>
                <description>
                    <![CDATA[ Python is an awesome language. Because of its simplicity, many people choose it as their first programming language.  Experienced programmers use Python all the time as well, thanks to its wide community, abundance of packages, and clear syntax. But ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/mutable-vs-immutable-objects-python/</link>
                <guid isPermaLink="false">66c17c4058ee0865d2671b5f</guid>
                
                    <category>
                        <![CDATA[ pythonic programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ immutability ]]>
                    </category>
                
                    <category>
                        <![CDATA[ mutable ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Omer Rosenbaum ]]>
                </dc:creator>
                <pubDate>Wed, 11 Nov 2020 19:01:31 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c95a1740569d1a4ca0dd3.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Python is an awesome language. Because of its simplicity, many people choose it as their first programming language. </p>
<p>Experienced programmers use Python all the time as well, thanks to its wide community, abundance of packages, and clear syntax.</p>
<p>But there's one issue that seems to confuse beginners as well as some experienced developers: Python objects. Specifically, the difference between <strong>mutable</strong> and <strong>immutable</strong> objects.</p>
<p>In this post we will deepen our knowledge of Python objects, learn the difference between <strong>mutable</strong> and <strong>immutable</strong> objects, and see how we can use the <strong>interpreter</strong> to better understand how Python operates. </p>
<p>We will use important functions and keywords such as <code>id</code> and <code>is</code>, and we'll understand the difference between <code>x == y</code> and <code>x is y</code>.</p>
<p>Are you up for it? Let's get started.</p>
<h1 id="heading-in-python-everything-is-an-object">In Python, everything is an object</h1>
<p>Unlike other programming languages where the language <em>supports</em> objects, in Python really <strong>everything</strong> is an object – including integers, lists, and even functions.</p>
<p>We can use our interpreter to verify that:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>isinstance(<span class="hljs-number">1</span>, object)
<span class="hljs-literal">True</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>isinstance(<span class="hljs-literal">False</span>, object)
<span class="hljs-literal">True</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_func</span>():</span>
   <span class="hljs-keyword">return</span> <span class="hljs-string">"hello"</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>isinstance(my_func, object)
<span class="hljs-literal">True</span>
</code></pre>
<p>Python has a built-in function, <code>id</code>, which returns the address of an object in memory. For example:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x = <span class="hljs-number">1</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>id(x)
<span class="hljs-number">1470416816</span>
</code></pre>
<p>Above, we created an <strong>object</strong> by the name of <code>x</code>, and assigned it the value of <code>1</code>. We then used <code>id(x)</code> and discovered that this object is found at the address <code>1470416816</code> in memory.</p>
<p>This allows us to check interesting things about Python. Let's say we create two variables in Python – one by the name of <code>x</code>, and one by the name of <code>y</code> – and assign them the same value. For example, here:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x = <span class="hljs-string">"I love Python!"</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>y = <span class="hljs-string">"I love Python!"</span>
</code></pre>
<p>We can use the equality operator (<code>==</code>) to verify that they indeed have the same value in Python's eyes:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x == y
<span class="hljs-literal">True</span>
</code></pre>
<p>But are these the same object in memory? In theory, there can be two very different scenarios here. </p>
<p>According to scenario <strong>(1)</strong>, we really have two different objects, one by the name of <code>x</code>, and another by the name of <code>y</code>, that just happen to have the same value. </p>
<p>Yet, it could also be the case that Python actually stores here only one object, which has two names that reference it – as shown in scenario <strong>(2)</strong>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We can use the <code>id</code> function introduced above to check this:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x = <span class="hljs-string">"I love Python!"</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>y = <span class="hljs-string">"I love Python!"</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>x == y
<span class="hljs-literal">True</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>id(x)
<span class="hljs-number">52889984</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>id(y)
<span class="hljs-number">52889384</span>
</code></pre>
<p>So as we can see, Python's behavior matches scenario (1) described above. Even though <code>x == y</code> in this example (that is, <code>x</code> and <code>y</code> have the same <em>values</em>), they are different objects in memory. This is because <code>id(x) != id(y)</code>, as we can verify explicitly:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>id(x) == id(y)
<span class="hljs-literal">False</span>
</code></pre>
<p>There is a shorter way to make the comparison above, and that is to use Python's <code>is</code> operator. Checking whether <code>x is y</code> is the same as checking <code>id(x) == id(y)</code>, which means whether <code>x</code> and <code>y</code> are the same object in memory:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x == y
<span class="hljs-literal">True</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>id(x) == id(y)
<span class="hljs-literal">False</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>x <span class="hljs-keyword">is</span> y
<span class="hljs-literal">False</span>
</code></pre>
<p>This sheds light on the important difference between the equality operator <code>==</code> and the identity operator <code>is</code>. </p>
<p>As you can see in the example above, it is completely possible for two names in Python (<code>x</code> and <code>y</code>) to be bound to two different objects (and thus, <code>x is y</code> is <code>False</code>), where these two objects have the same value (so <code>x == y</code> is <code>True</code>).</p>
<p>How can we create another variable that points to the same object that <code>x</code> is pointing to? We can simply use the assignment operator <code>=</code>, like so:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x = <span class="hljs-string">"I love Python!"</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>z = x
</code></pre>
<p>To verify that they indeed point to the same object, we can use the <code>is</code> operator:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x <span class="hljs-keyword">is</span> z
<span class="hljs-literal">True</span>
</code></pre>
<p>Of course, this means they have the same address in memory, as we can verify explicitly by using <code>id</code>:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>id(x)
<span class="hljs-number">54221824</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>id(z)
<span class="hljs-number">54221824</span>
</code></pre>
<p>And, of course, they have the same value, so we expect <code>x == z</code> to return <code>True</code> as well:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x == z
<span class="hljs-literal">True</span>
</code></pre>
<h1 id="heading-mutable-and-immutable-objects-in-python">Mutable and immutable objects in Python</h1>
<p>We have said that everything in Python is an object, yet there is an important distinction between objects. Some objects are <strong>mutable</strong> while some are <strong>immutable</strong>. </p>
<p>As I mentioned before, this fact causes confusion for many people who are new to Python, so we are going to make sure it's clear.</p>
<h2 id="heading-immutable-objects-in-python">Immutable objects in Python</h2>
<p>For some types in Python, once we have created instances of those types, they never change. They are <strong>immutable</strong>. </p>
<p>For example, <code>int</code> objects are immutable in Python. What will happen if we try to change the value of an <code>int</code> object?</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x = <span class="hljs-number">24601</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>x
<span class="hljs-number">24601</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>x = <span class="hljs-number">24602</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>x
<span class="hljs-number">24602</span>
</code></pre>
<p>Well, it seems that we changed <code>x</code> successfully. This is exactly where many people get confused. What exactly happened under the hood here? Let's use <code>id</code> to further investigate:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x = <span class="hljs-number">24601</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>x
<span class="hljs-number">24601</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>id(x)
<span class="hljs-number">1470416816</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>x = <span class="hljs-number">24602</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>x
<span class="hljs-number">24602</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>id(x)
<span class="hljs-number">1470416832</span>
</code></pre>
<p>So we can see that by assigning <code>x = 24602</code>, we didn't change the value of the object that <code>x</code> had been bound to before. Rather, we created a new object, and bound the name <code>x</code> to it. </p>
<p>So after assigning <code>24601</code> to <code>x</code> by using <code>x = 24601</code>, we had the following state:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-46.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And after using <code>x = 24602</code>, we created a new object, and bound the name <code>x</code> to this new object. The other object with the value of <code>24601</code> is no longer reachable by <code>x</code> (or any other name in this case):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-47.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Whenever we assign a new value to a name (in the above example - <code>x</code>) that is bound to an <code>int</code> object, we actually change the binding of that name to another object. </p>
<p>The same applies for <code>tuple</code>s, strings (<code>str</code> objects), and <code>bool</code>s as well. In other words, <code>int</code> (and other number types such as <code>float</code>), <code>tuple</code>, <code>bool</code>, and <code>str</code> objects are <strong>immutable</strong>.</p>
<p>Let's test this hypothesis. What happens if we create a <code>tuple</code> object, and then give it a different value? </p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>my_tuple = (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>id(my_tuple)
<span class="hljs-number">54263304</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>my_tuple = (<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>id(my_tuple)
<span class="hljs-number">56898184</span>
</code></pre>
<p>Just like an <code>int</code> object, we can see that our assignment actually changed the object that the name <code>my_tuple</code> is bound to.</p>
<p>What happens if we try to change one of the <code>tuple</code>'s elements?</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>my_tuple[<span class="hljs-number">0</span>] = <span class="hljs-string">'a new value'</span>
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;stdin&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
TypeError: <span class="hljs-string">'tuple'</span> object does <span class="hljs-keyword">not</span> support item assignment
</code></pre>
<p>As we can see, Python doesn't allow us to modify <code>my_tuple</code>'s contents, as it is immutable.</p>
<h2 id="heading-mutable-objects-in-python">Mutable objects in Python</h2>
<p>Some types in Python can be modified after creation, and they are called <strong>mutable</strong>. For example, we know that we can modify the contents of a <code>list</code> object:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>my_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>my_list[<span class="hljs-number">0</span>] = <span class="hljs-string">'a new value'</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>my_list
[<span class="hljs-string">'a new value'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
</code></pre>
<p>Does that mean we actually created a new object when assigning a new value to the first element of <code>my_list</code>? Again, we can use <code>id</code> to check:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>my_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>id(my_list)
<span class="hljs-number">55834760</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>my_list
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]

<span class="hljs-meta">&gt;&gt;&gt; </span>my_list[<span class="hljs-number">0</span>] = <span class="hljs-string">'a new value'</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>id(my_list)
<span class="hljs-number">55834760</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>my_list
[<span class="hljs-string">'a new value'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
</code></pre>
<p>So our first assignment <code>my_list = [1, 2, 3]</code> created an object in the address <code>55834760</code>, with the values of <code>1</code>, <code>2</code>, and <code>3</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-22.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We then modified the first element of this <code>list</code> object using <code>my_list[0] = 'a new value'</code>, that is - without creating a new <code>list</code> object:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-23.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now, let us create two names – <code>x</code> and <code>y</code>, both bound to the same <code>list</code> object. We can verify that either by using <code>is</code>, or by explicitly checking their <code>id</code>s:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x = y = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>x <span class="hljs-keyword">is</span> y
<span class="hljs-literal">True</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>id(x)
<span class="hljs-number">18349096</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>id(y)
<span class="hljs-number">18349096</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>id(x) == id(y)
<span class="hljs-literal">True</span>
</code></pre>
<p>What happens now if we use <code>x.append(3)</code>? That is, if we add a new element (<code>3</code>) to the object by the name of <code>x</code>?</p>
<p>Will <code>x</code> by changed? Will <code>y</code>?</p>
<p>Well, as we already know, they are basically two names of the same object:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-28.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Since this object is changed, when we check its names we can see the new value:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x.append(<span class="hljs-number">3</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>x
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]

<span class="hljs-meta">&gt;&gt;&gt; </span>y
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
</code></pre>
<p>Note that <code>x</code> and <code>y</code> have the same <code>id</code> as before – as they are still bound to the same <code>list</code> object:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>id(x)
<span class="hljs-number">18349096</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>id(y)
<span class="hljs-number">18349096</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-27.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In addition to <code>list</code>s, other Python types that are mutable include <code>set</code>s and <code>dict</code>s.</p>
<h1 id="heading-implications-for-dictionary-keys-in-python">Implications for dictionary keys in Python</h1>
<p>Dictionaries (<code>dict</code> objects) are commonly used in Python. As a quick reminder, we define them like so:</p>
<pre><code class="lang-python">my_dict = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Omer"</span>, <span class="hljs-string">"number_of_pets"</span>: <span class="hljs-number">1</span>}
</code></pre>
<p>We can then access a specific element by its key name:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>my_dict[<span class="hljs-string">"name"</span>]
<span class="hljs-string">'Omer'</span>
</code></pre>
<p>Dictionaries are <strong>mutable</strong>, so we can change their content after creation. At any given moment, a key in the dictionary can point to one element only:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>my_dict[<span class="hljs-string">"name"</span>] = <span class="hljs-string">"John"</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>my_dict[<span class="hljs-string">"name"</span>]
<span class="hljs-string">'John'</span>
</code></pre>
<p>It is interesting to note that a <strong>dictionary's keys must be immutable</strong>:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>my_dict = {[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>]: <span class="hljs-string">"Hello"</span>}
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;stdin&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
TypeError: unhashable type: <span class="hljs-string">'list'</span>
</code></pre>
<p>Why is that so? </p>
<p>Let's consider the following hypothetical scenario (note: the snippet below can't really be run in Python):</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>y = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>my_dict = {x: <span class="hljs-string">'a'</span>, y: <span class="hljs-string">'b'</span>}
</code></pre>
<p>So far, things don't seem that bad. We'd assume that if we access <code>my_dict</code> with the key of <code>[1, 2]</code>, we will get the corresponding value of <code>'a'</code>, and if we access the key <code>[1, 2, 3]</code>, we will get the value <code>'b'</code>. </p>
<p>Now, what would happen if we attempted to use:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>x.append(<span class="hljs-number">3</span>)
</code></pre>
<p>In this case, <code>x</code> would have the value of <code>[1, 2, 3]</code>, and <code>y</code> would also have the value of <code>[1, 2, 3]</code>. What should we get when we ask for <code>my_dict[[1, 2, 3]]</code>? Will it be <code>'a'</code> or <code>'b'</code>? To avoid such cases, Python simply doesn't allow dictionary keys to be mutable.</p>
<h1 id="heading-taking-things-a-bit-further">Taking things a bit further</h1>
<p>Let's try to apply our knowledge to a case that is a bit more interesting.</p>
<p>Below, we define a <code>list</code> (a <strong>mutable</strong> object) and a <code>tuple</code> (an <strong>immutable</strong> object). The <code>list</code> includes a <code>tuple</code>, and the <code>tuple</code> includes a <code>list</code>:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>my_list = [(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>), <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>my_tuple = ([<span class="hljs-number">1</span>, <span class="hljs-number">1</span>], <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>type(my_list)
&lt;<span class="hljs-class"><span class="hljs-keyword">class</span> '<span class="hljs-title">list</span>'&gt;

&gt;&gt;&gt; <span class="hljs-title">type</span>(<span class="hljs-params">my_list[<span class="hljs-number">0</span>]</span>)
&lt;<span class="hljs-title">class</span> '<span class="hljs-title">tuple</span>'&gt;

&gt;&gt;&gt; <span class="hljs-title">type</span>(<span class="hljs-params">my_tuple</span>)
&lt;<span class="hljs-title">class</span> '<span class="hljs-title">tuple</span>'&gt;

&gt;&gt;&gt; <span class="hljs-title">type</span>(<span class="hljs-params">my_tuple[<span class="hljs-number">0</span>]</span>)
&lt;<span class="hljs-title">class</span> '<span class="hljs-title">list</span>'&gt;</span>
</code></pre>
<p>So far so good. Now, try to think for yourself – what will happen when we try to execute each of the following statements?</p>
<p>(1) <code>&gt;&gt;&gt; my_list[0][0] = 'Changed!'</code></p>
<p>(2) <code>&gt;&gt;&gt; my_tuple[0][0] = 'Changed!'</code></p>
<p>In statement (1), what we are trying to do is change <code>my_list</code>'s first element, that is, a <code>tuple</code>. Since a <code>tuple</code> is <strong>immutable</strong>, this attempt is destined to fail:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>my_list[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>] = <span class="hljs-string">'Changed!'</span>
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;stdin&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
TypeError: <span class="hljs-string">'tuple'</span> object does <span class="hljs-keyword">not</span> support item assignment
</code></pre>
<p>Note that what we were trying to do is <em>not</em> change the list, but rather – change the contents of its first element. </p>
<p>Let's consider statement (2). In this case, we are accessing <code>my_tuple</code>'s first element, which happens to be a <code>list</code>, and modify it. Let's further investigate this case and look at the addresses of these elements:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>my_tuple = ([<span class="hljs-number">1</span>, <span class="hljs-number">1</span>], <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>id(my_tuple)
<span class="hljs-number">20551816</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>type(my_tuple[<span class="hljs-number">0</span>])
&lt;<span class="hljs-class"><span class="hljs-keyword">class</span> '<span class="hljs-title">list</span>'&gt;

&gt;&gt;&gt; <span class="hljs-title">id</span>(<span class="hljs-params">my_tuple[<span class="hljs-number">0</span>]</span>)
20446248</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-29.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>When we change <code>my_tuple[0][0]</code>, we do not really change <code>my_tuple</code> at all! Indeed, after the change, <code>my_tuple</code>'s first element will still be the object whose address in memory is <code>20446248</code>. We do, however, change the value of that object:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>my_tuple[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>] = <span class="hljs-string">'Changed!'</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>id(my_tuple)
<span class="hljs-number">20551816</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>id(my_tuple[<span class="hljs-number">0</span>])
<span class="hljs-number">20446248</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>my_tuple
([<span class="hljs-string">'Changed!'</span>, <span class="hljs-number">1</span>], <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-48.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Since we only modified the value of <code>my_tuple[0]</code>, which is a mutable <code>list</code> object, this operation was indeed allowed by Python.</p>
<h1 id="heading-recap">Recap</h1>
<p>In this post we learned about Python objects. We said that in Python <strong>everything is an object</strong>, and got to use <code>id</code> and <code>is</code> to deepen our understanding of what's happening under the hood when using Python to create and modify objects.</p>
<p>We also learned the difference between <strong>mutable</strong> objects, that can be modified after creation, and <strong>immutable</strong> objects, which cannot. </p>
<p>We saw that when we ask Python to modify an immutable object that is bound to a certain name, we actually create a new object and bind that name to it.</p>
<p>We then learned why dictionary keys have to be <strong>immutable</strong> in Python.</p>
<p>Understanding how Python "sees" objects is a key to becoming a better Python programmer. I hope this post has helped you on your journey to mastering Python.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/omer-rosenbaum-034a08b9/"><em>Omer Rosenbaum</em></a><em>,</em> <a target="_blank" href="https://swimm.io/"><em>Swimm</em></a><em>’s Chief Technology Officer. Cyber training expert and Founder of Checkpoint Security Academy. Author of</em> <a target="_blank" href="https://data.cyber.org.il/networks/networks.pdf"><em>Computer Networks (in Hebrew)</em></a><em>. Visit My</em> <a target="_blank" href="https://www.youtube.com/watch?v=79jlgESHzKQ&amp;list=PL9lx0DXCC4BMS7dB7vsrKI5wzFyVIk2Kg"><em>YouTube Channel</em></a><em>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Object Keys Tutorial – How to Use a JS Key-Value Pair ]]>
                </title>
                <description>
                    <![CDATA[ By Amy Haddad You can group related data together into a single data structure by using a JavaScript object, like this: const desk = {    height: "4 feet",    weight: "30 pounds",    color: "brown",    material: "wood",  }; An ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-object-keys-tutorial-how-to-use-a-js-key-value-pair/</link>
                <guid isPermaLink="false">66d45da4052ad259f07e4a73</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 11 Nov 2020 18:35:34 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/11/objects.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Amy Haddad</p>
<p>You can group related data together into a single data structure by using a JavaScript object, like this:</p>
<pre><code class="lang-JavaScript"><span class="hljs-keyword">const</span> desk = {
   <span class="hljs-attr">height</span>: <span class="hljs-string">"4 feet"</span>,
   <span class="hljs-attr">weight</span>: <span class="hljs-string">"30 pounds"</span>,
   <span class="hljs-attr">color</span>: <span class="hljs-string">"brown"</span>,
   <span class="hljs-attr">material</span>: <span class="hljs-string">"wood"</span>,
 };
</code></pre>
<p>An object contains properties, or key-value pairs. The <code>desk</code> object above has four properties. Each property has a name, which is also called a key, and a corresponding value. </p>
<p>For instance, the key <code>height</code> has the value <code>"4 feet"</code>. Together, the key and value make up a single property. </p>
<pre><code class="lang-JavaScript">height: <span class="hljs-string">"4 feet"</span>,
</code></pre>
<p>The <code>desk</code> object contains data about a desk. In fact, this is a reason why you’d use a JavaScript object: to store data. It’s also simple to retrieve the data that you store in an object. These aspects make objects very useful. </p>
<p>This article will get you up and running with JavaScript objects:</p>
<ul>
<li>how to create an object </li>
<li>how to store data in an object</li>
<li>and retrieve data from it.</li>
</ul>
<p>Let’s start by creating an object.</p>
<h1 id="heading-how-to-create-an-object-in-javascript">How to Create an Object in JavaScript</h1>
<p>I'll create an object called <code>pizza</code> below, and add key-value pairs to it. </p>
<pre><code class="lang-javaScript"><span class="hljs-keyword">const</span> pizza = {
   <span class="hljs-attr">topping</span>: <span class="hljs-string">"cheese"</span>,
   <span class="hljs-attr">sauce</span>: <span class="hljs-string">"marinara"</span>,
   <span class="hljs-attr">size</span>: <span class="hljs-string">"small"</span>
};
</code></pre>
<p>The keys are to the left of the colon <code>:</code> and the values are to the right of it. Each key-value pair is a <code>property</code>. There are three properties in this example:</p>
<ul>
<li>The key <strong>topping</strong> has a value <strong>“cheese”</strong>.</li>
<li>The key <strong>sauce</strong> has a value <strong>“marinara”</strong>.</li>
<li>The key <strong>size</strong> has a value <strong>“small”</strong>.</li>
</ul>
<p>Each property is separated by a comma. All of the properties are wrapped in curly braces. </p>
<p>This is the basic object syntax. But there are a few rules to keep in mind when creating JavaScript objects.</p>
<h3 id="heading-object-keys-in-javascript">Object Keys in JavaScript</h3>
<p>Each key in your JavaScript object must be a string, symbol, or number.</p>
<p>Take a close look at the example below. The key names <strong><code>1</code></strong> and <strong><code>2</code></strong> are actually coerced into strings.</p>
<pre><code class="lang-javaScript"><span class="hljs-keyword">const</span> shoppingCart = {
   <span class="hljs-number">1</span>: <span class="hljs-string">"apple"</span>,
   <span class="hljs-number">2</span>: <span class="hljs-string">"oranges"</span>
};
</code></pre>
<p>It’s a difference made clear when you print the object.</p>
<pre><code class="lang-javaScript"><span class="hljs-built_in">console</span>.log(shoppingCart);
<span class="hljs-comment">//Result: { '1': 'apple', '2': 'oranges' }</span>
</code></pre>
<p>There’s another rule to keep in mind about key names: if your key name contains spaces, you need to wrap it in quotes.</p>
<p>Take a look at the <code>programmer</code> object below. Notice the last key name, <code>"current project name"</code> . This key name contains spaces so, I wrapped it in quotes.</p>
<pre><code class="lang-javaScript"><span class="hljs-keyword">const</span> programmer = {
   <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Phil"</span>,
   <span class="hljs-attr">age</span>: <span class="hljs-number">21</span>,
   <span class="hljs-attr">backendDeveloper</span>: <span class="hljs-literal">true</span>,
   <span class="hljs-attr">languages</span>: [<span class="hljs-string">"Python"</span>, <span class="hljs-string">"JavaScript"</span>, <span class="hljs-string">"Java"</span>, <span class="hljs-string">"C++"</span>],
   <span class="hljs-string">"current project name"</span>: <span class="hljs-string">"The Amazing App"</span>
};
</code></pre>
<h3 id="heading-object-values-in-javascript">Object Values in JavaScript</h3>
<p>A value, on the other hand, can be any data type, including an array, number, or boolean. The values in the above example contain these types: string, integer, boolean, and an array.</p>
<p>You can even use a function as a value, in which case it’s known as a method. <code>sounds()</code>, in the object below, is an example. </p>
<pre><code class="lang-javaScript"><span class="hljs-keyword">const</span> animal = {
   <span class="hljs-attr">type</span>: <span class="hljs-string">"cat"</span>,
   <span class="hljs-attr">name</span>: <span class="hljs-string">"kitty"</span>,
   sounds() { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"meow meow"</span>) }
};
</code></pre>
<p>Now say you want to add or delete a key-value pair. Or you simply want to retrieve an object’s value.</p>
<p>You can do these things by using dot or bracket notation, which we’ll tackle next.</p>
<h1 id="heading-how-dot-notation-and-bracket-notation-work-in-javascript">How Dot Notation and Bracket Notation Work in JavaScript</h1>
<p>Dot notation and bracket notation are two ways to access and use an object’s properties. You’ll probably find yourself reaching for dot notation more often, so we'll start with that.</p>
<h3 id="heading-how-to-add-a-key-value-pair-with-dot-notation-in-javascript">How to Add a Key-Value Pair with Dot Notation in JavaScript</h3>
<p>I'll create an empty <code>book</code> object below.</p>
<pre><code class="lang-JavaScript"><span class="hljs-keyword">const</span> book = {};
</code></pre>
<p>To add a key-value pair using dot notation, use the syntax:</p>
<p> <code>objectName.keyName = value</code></p>
<p>This is the code to add the key (author) and value ("Jane Smith") to the <code>book</code> object: </p>
<pre><code class="lang-JavaScript">book.author = <span class="hljs-string">"Jane Smith"</span>;
</code></pre>
<p>Here's a breakdown of the above code:</p>
<ul>
<li><code>book</code> is the object's name</li>
<li><code>.</code> (dot)</li>
<li><code>author</code> is the key name </li>
<li><code>=</code> (equals)</li>
<li><code>"Jane Smith"</code> is the value</li>
</ul>
<p>When I print the book object, I’ll see the newly added key-value pair.</p>
<pre><code class="lang-javaScript"><span class="hljs-built_in">console</span>.log(book);
<span class="hljs-comment">//Result: { author: 'Jane Smith' }</span>
</code></pre>
<p>I’ll add another key-value pair to the <code>book</code> object.</p>
<pre><code class="lang-JavaScript">book.publicationYear = <span class="hljs-number">2006</span>;
</code></pre>
<p>The <code>book</code> object now has two properties.</p>
<pre><code class="lang-javaScript"><span class="hljs-built_in">console</span>.log(book);
<span class="hljs-comment">//Result: { author: 'Jane Smith', publicationYear: 2006 }</span>
</code></pre>
<h3 id="heading-how-to-access-data-in-a-javascript-object-using-dot-notation">How to Access Data in a JavaScript Object Using Dot Notation</h3>
<p>You can also use dot notation on a key to <em>access</em> the related value. </p>
<p>Consider this <code>basketballPlayer</code> object.</p>
<pre><code class="lang-javaScript"><span class="hljs-keyword">const</span> basketballPlayer = {
   <span class="hljs-attr">name</span>: <span class="hljs-string">"James"</span>,
   <span class="hljs-attr">averagePointsPerGame</span>: <span class="hljs-number">20</span>,
   <span class="hljs-attr">height</span>: <span class="hljs-string">"6 feet, 2 inches"</span>,
   <span class="hljs-attr">position</span>: <span class="hljs-string">"shooting guard"</span>
};
</code></pre>
<p>Say you want to retrieve the value “shooting guard.” This is the syntax to use: </p>
<p><code>objectName.keyName</code></p>
<p>Let's put this syntax to use to get and print the "shooting guard" value.</p>
<pre><code class="lang-javaScript"><span class="hljs-built_in">console</span>.log(basketballPlayer.position);
<span class="hljs-comment">//Result: shooting guard</span>
</code></pre>
<p>Here's a breakdown of the above code:</p>
<ul>
<li><code>basketballPlayer</code> is the object's name</li>
<li><code>.</code> (dot)</li>
<li><code>position</code> is the key name</li>
</ul>
<p>This is another example.</p>
<pre><code class="lang-javaScript"><span class="hljs-built_in">console</span>.log(basketballPlayer.name);
<span class="hljs-comment">//Result: James</span>
</code></pre>
<h3 id="heading-how-to-delete-a-key-value-pair-in-javascript">How to Delete a Key-Value Pair in JavaScript</h3>
<p>To delete a key-value pair use the <code>delete</code> operator. This the syntax: </p>
<p><code>delete objectName.keyName</code></p>
<p>So to delete the <code>height</code> key and its value from the <code>basketballPlayer</code> object, you’d write this code: </p>
<pre><code class="lang-JavaScript"><span class="hljs-keyword">delete</span> basketballPlayer.height;
<span class="hljs-string">`</span>
</code></pre>
<p>As a result, the <code>basketballPlayer</code> object now has three key-value pairs.</p>
<pre><code class="lang-javaScript"><span class="hljs-built_in">console</span>.log(basketballPlayer);
<span class="hljs-comment">//Result: { name: 'James', averagePointsPerGame: 20, position: 'shooting guard' }</span>
</code></pre>
<p>You’ll probably find yourself reaching for dot notation frequently, though there are certain requirements to be aware of.</p>
<p>When using dot notation, key names can’t contain spaces, hyphens, or start with a number.</p>
<p>For example, say I try to add a key that contains spaces using dot notation. I’ll get an error.</p>
<pre><code class="lang-javaScript">basketballPlayer.shooting percentage = <span class="hljs-string">"75%"</span>;
<span class="hljs-comment">//Results in an error</span>
</code></pre>
<p>So dot notation won’t work in every situation. That’s why there’s another option: bracket notation.</p>
<h3 id="heading-how-to-add-a-key-value-pair-using-bracket-notation-in-javascript">How to Add a Key-Value Pair Using Bracket Notation in JavaScript</h3>
<p>Just like dot notation, you can use bracket notation to add a key-value pair to an object. </p>
<p>Bracket notation offers more flexibility than dot notation. That’s because key names <em>can</em> include spaces and hyphens, and they can start with numbers.</p>
<p>I'll create an <code>employee</code> object below.</p>
<pre><code class="lang-JavaScript"><span class="hljs-keyword">const</span> employee = {};
</code></pre>
<p>Now I want to add a key-value pair using bracket notation. This is the syntax: </p>
<p><code>objectName[“keyName”] = value</code></p>
<p>So this is how I’d add the key (occupation) and value (sales) to the employee object: </p>
<pre><code class="lang-JavaScript">employee[<span class="hljs-string">"occupation"</span>] = <span class="hljs-string">"sales"</span>;
</code></pre>
<p>Here's a breakdown of the above code:</p>
<ul>
<li><code>employee</code> is the object's name</li>
<li><code>"occupation"</code> is the key name </li>
<li><code>=</code> (equals)</li>
<li><code>"sales"</code> is the value</li>
</ul>
<p>Below are several more examples that use bracket notation's flexibility to add a variety of key-value pairs.</p>
<pre><code class="lang-javaScript"><span class="hljs-comment">//Add multi-word key name</span>
employee[<span class="hljs-string">"travels frequently"</span>] = <span class="hljs-literal">true</span>;

<span class="hljs-comment">//Add key name that starts with a number and includes a hyphen</span>
employee[<span class="hljs-string">"1st-territory"</span>] = <span class="hljs-string">"Chicago"</span>;

<span class="hljs-comment">//Add a key name that starts with a number</span>
employee[<span class="hljs-string">"25"</span>] = <span class="hljs-string">"total customers"</span>;
</code></pre>
<p>When I print the <code>employee</code> object, it looks like this:</p>
<pre><code class="lang-javaScript">{
  <span class="hljs-string">'25'</span>: <span class="hljs-string">'total customers'</span>,
  <span class="hljs-attr">occupation</span>: <span class="hljs-string">'sales'</span>,
  <span class="hljs-string">'travels frequently'</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-string">'1st-territory'</span>: <span class="hljs-string">'Chicago'</span>
}
</code></pre>
<p>With this information in mind, we can add the “shooting percentage” key to the <code>basketballPlayer</code> object from above.</p>
<pre><code class="lang-javaScript"><span class="hljs-keyword">const</span> basketballPlayer = {
   <span class="hljs-attr">name</span>: <span class="hljs-string">"James"</span>,
   <span class="hljs-attr">averagePointsPerGame</span>: <span class="hljs-number">20</span>,
   <span class="hljs-attr">height</span>: <span class="hljs-string">"6 feet, 2 inches"</span>,
   <span class="hljs-attr">position</span>: <span class="hljs-string">"shooting guard"</span>
};
</code></pre>
<p>You may remember that dot notation left us with an error when we tried to add a key that included spaces.</p>
<pre><code class="lang-JavaScript">basketballPlayer.shooting percentage = <span class="hljs-string">"75%"</span>;
<span class="hljs-comment">//Results in an error</span>
</code></pre>
<p>But bracket notation leaves us error-free, as you can see here:</p>
<pre><code class="lang-JavaScript">basketballPlayer[<span class="hljs-string">"shooting percentage"</span>] = <span class="hljs-string">"75%"</span>;
</code></pre>
<p>This is the result when I print the object:</p>
<pre><code class="lang-JavaScript">{
  <span class="hljs-attr">name</span>: <span class="hljs-string">'James'</span>,
  <span class="hljs-attr">averagePointsPerGame</span>: <span class="hljs-number">20</span>,
  <span class="hljs-attr">height</span>: <span class="hljs-string">'6 feet, 2 inches'</span>,
  <span class="hljs-attr">position</span>: <span class="hljs-string">'shooting guard'</span>,
  <span class="hljs-string">'shooting percentage'</span>: <span class="hljs-string">'75%'</span>
}
</code></pre>
<h3 id="heading-how-to-access-data-in-a-javascript-object-using-bracket-notation">How to Access Data in a JavaScript Object Using Bracket Notation</h3>
<p>You can also use bracket notation on a key to <em>access</em> the related value.</p>
<p>Recall the <code>animal</code> object from the start of the article.</p>
<pre><code class="lang-JavaScript"><span class="hljs-keyword">const</span> animal = {
   <span class="hljs-attr">type</span>: <span class="hljs-string">"cat"</span>,
   <span class="hljs-attr">name</span>: <span class="hljs-string">"kitty"</span>,
   sounds() { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"meow meow"</span>) }
};
</code></pre>
<p>Let's get the value associated with the key, <code>name</code>. To do this, wrap the key name quotes and put it in brackets. This is the syntax: </p>
<p><code>objectName[“keyName”]</code></p>
<p>Here's the code you'd write with bracket notation: <code>animal["name"];</code>.    </p>
<p>This is a breakdown of the above code:</p>
<ul>
<li><code>animal</code> is the object's name</li>
<li><code>["name"]</code> is the key name enclosed in square brackets</li>
</ul>
<p>Here’s another example.</p>
<pre><code class="lang-JavaScript"><span class="hljs-built_in">console</span>.log(animal[<span class="hljs-string">"sounds"</span>]());

<span class="hljs-comment">//Result: </span>
meow meow
<span class="hljs-literal">undefined</span>
</code></pre>
<p>Note that <code>sounds()</code> is a method, which is why I added the parentheses at the end to invoke it.</p>
<p>This is how you’d invoke a method using dot notation.</p>
<pre><code class="lang-JavaScript"><span class="hljs-built_in">console</span>.log(animal.sounds());

<span class="hljs-comment">//Result: </span>
meow meow
<span class="hljs-literal">undefined</span>
</code></pre>
<h1 id="heading-javascript-object-methods">JavaScript Object Methods</h1>
<p>You know how to access specific properties. But what if you want <em>all</em> of the keys or <em>all</em> of the values from an object?</p>
<p>There are two methods that will give you the information you need.</p>
<pre><code class="lang-JavaScript"><span class="hljs-keyword">const</span> runner = {
   <span class="hljs-attr">name</span>: <span class="hljs-string">"Jessica"</span>,
   <span class="hljs-attr">age</span>: <span class="hljs-number">20</span>,
   <span class="hljs-attr">milesPerWeek</span>: <span class="hljs-number">40</span>,
   <span class="hljs-attr">race</span>: <span class="hljs-string">"marathon"</span>
};
</code></pre>
<p>Use the <code>Object.keys()</code> method to retrieve all of the key names from an object.</p>
<p>This is the syntax:</p>
<p><code>Object.keys(objectName)</code></p>
<p>We can use this method on the above <code>runner</code> object.</p>
<pre><code class="lang-JavaScript"><span class="hljs-built_in">Object</span>.keys(runner);
</code></pre>
<p>If you print the result, you’ll get an array of the object’s keys.</p>
<pre><code class="lang-JavaScript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.keys(runner));
<span class="hljs-comment">//Result: [ 'name', 'age', 'milesPerWeek', 'race' ]</span>
</code></pre>
<p>Likewise, you can use the <code>Object.values()</code> method to get all of the values from an object. This is the syntax: </p>
<p><code>Object.values(objectName)</code></p>
<p>Now we'll get all of the values from the <code>runner</code> object.</p>
<pre><code class="lang-JavaScript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.values(runner));
<span class="hljs-comment">//Result: [ 'Jessica', 20, 40, 'marathon' ]</span>
</code></pre>
<p>We’ve covered a lot of ground. Here’s a summary of the key ideas:</p>
<p><strong>Objects:</strong></p>
<ul>
<li>Use objects to store data as properties (key-value pairs).</li>
<li>Key names must be strings, symbols, or numbers.</li>
<li>Values can be any type.</li>
</ul>
<p><strong>Access object properties:</strong></p>
<ul>
<li>Dot notation: <code>objectName.keyName</code></li>
<li>Bracket notation: <code>objectName[“keyName”]</code></li>
</ul>
<p><strong>Delete a property:</strong></p>
<ul>
<li><code>delete objectName.keyName</code>  </li>
</ul>
<p>There’s a lot you can do with objects. And now you’ve got some of the basics so you can take advantage of this powerful JavaScript data type.  </p>
<p><em>I write about learning to program, and the best ways to go about it on <a target="_blank" href="http://amymhaddad.com/">amymhaddad.com</a>.</em> I also <em>tweet about programming, learning, and productivity: <a target="_blank" href="https://twitter.com/amymhaddad">@amymhaddad</a></em>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Count Objects in an Array ]]>
                </title>
                <description>
                    <![CDATA[ Knowing how to quickly iterate through an array and count objects is deceptively simple. The length() method will tell you the total number of values in the array, but what if you only want to count those values based on certain conditions? For examp... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-count-objects-in-an-array/</link>
                <guid isPermaLink="false">66c350ddf41767c3c96bad05</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 02 Jun 2020 02:18:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9a9a740569d1a4ca2696.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Knowing how to quickly iterate through an array and count objects is deceptively simple. The <code>length()</code> method will tell you the total number of values in the array, but what if you only want to count those values based on certain conditions?</p>
<p>For example, imagine you have an array like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storage = [
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'1'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'2'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'3'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'4'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'5'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'6'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'7'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'1'</span> },
];
</code></pre>
<p>And you only want to count the number of objects with <code>status</code> set to <code>'0'</code>.</p>
<p>Like with just about everything in programming, there are a number of ways to do this. We'll go through a few of the common methods below.</p>
<h2 id="heading-use-a-for-loop">Use a <code>for</code> loop</h2>
<p>Probably the easiest way would be to declare a <code>counter</code> variable, loop through the array, and iterate <code>counter</code> only if <code>status</code> is equal to <code>'0'</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storage = [
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'1'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'2'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'3'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'4'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'5'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'6'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'7'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'1'</span> },
];

<span class="hljs-keyword">let</span> counter = <span class="hljs-number">0</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; storage.length; i++) {
  <span class="hljs-keyword">if</span> (storage[i].status === <span class="hljs-string">'0'</span>) counter++;
}

<span class="hljs-built_in">console</span>.log(counter); <span class="hljs-comment">// 6</span>
</code></pre>
<p>You could simplify this a bit by using a <code>for...of</code> loop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storage = [
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'1'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'2'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'3'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'4'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'5'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'6'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'7'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'1'</span> },
];

<span class="hljs-keyword">let</span> counter = <span class="hljs-number">0</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> obj <span class="hljs-keyword">of</span> storage) {
  <span class="hljs-keyword">if</span> (obj.status === <span class="hljs-string">'0'</span>) counter++;
}

<span class="hljs-built_in">console</span>.log(counter); <span class="hljs-comment">// 6</span>
</code></pre>
<p>Also, you could create a function to do the same thing if you have other arrays of objects to count conditionally:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storage = [
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'1'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'2'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'3'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'4'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'5'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'6'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'7'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'1'</span> },
];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">statusCounter</span>(<span class="hljs-params">inputs</span>) </span>{
  <span class="hljs-keyword">let</span> counter = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> input <span class="hljs-keyword">of</span> inputs) {
    <span class="hljs-keyword">if</span> (input.status === <span class="hljs-string">'0'</span>) counter += <span class="hljs-number">1</span>;
  }
  <span class="hljs-keyword">return</span> counter;
}

statusCounter(storage); <span class="hljs-comment">// 6</span>
</code></pre>
<h2 id="heading-use-array-methods">Use array methods</h2>
<p>JavaScript includes a bunch of <a target="_blank" href="https://www.freecodecamp.org/news/javascript-standard-objects-arrays/">helpful methods</a> when working with arrays. Each one can be chained to an array and passed different parameters to work with while iterating through the elements in the array.</p>
<p>The two we'll look at are <code>filter()</code> and <code>reduce()</code>.</p>
<h3 id="heading-filter"><code>filter()</code></h3>
<p>The filter method does just that – it iterates through each element in the array and filters out all elements that don't meet the condition(s) you provide. It then returns a new array with all the elements that returned true based on your condition(s).</p>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storage = [
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'1'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'2'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'3'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'4'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'5'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'6'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'7'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'1'</span> },
];

<span class="hljs-keyword">const</span> count = storage.filter(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>)</span>{
  <span class="hljs-keyword">if</span> (item.status === <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
});

<span class="hljs-comment">/*
[
  { data: '1', status: '0' },
  { data: '2', status: '0' },
  { data: '3', status: '0' },
  { data: '4', status: '0' },
  { data: '5', status: '0' },
  { data: '6', status: '0' }
] 
*/</span>
</code></pre>
<p>Now that you've filtered out the object with <code>status: '1'</code>, just call the <code>length()</code> method on the new array to get the total count of objects with <code>status: '1'</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storage = [
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'1'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'2'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'3'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'4'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'5'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'6'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'7'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'1'</span> },
];

<span class="hljs-keyword">const</span> count = storage.filter(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>)</span>{
  <span class="hljs-keyword">if</span> (item.status === <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}).length; <span class="hljs-comment">// 6</span>
</code></pre>
<p>But this can be shortened a lot with ES6 syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storage = [
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'1'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'2'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'3'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'4'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'5'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'6'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'7'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'1'</span> },
];

<span class="hljs-keyword">const</span> count = storage.filter(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> item.status === <span class="hljs-string">'0'</span>).length; <span class="hljs-comment">// 6</span>
</code></pre>
<h3 id="heading-reduce"><code>reduce()</code></h3>
<p>Think of the <code>reduce()</code> method like a Swiss army knife – it's extremely flexible, and lets you take an array as input and transform it into just about anything. Even better, like <code>filter()</code>, this method returns a new array, leaving the original unchanged.</p>
<p>You can read more about <code>reduce()</code> in <a target="_blank" href="https://www.freecodecamp.org/news/the-ultimate-guide-to-javascript-array-methods-reduce/">this article</a>.</p>
<p>For our purposes, we want to take an array, examine its contents, and produce a number. Here's a simple way to do that:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storage = [
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'1'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'2'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'3'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'4'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'5'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'6'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'7'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'1'</span> },
];

<span class="hljs-keyword">const</span> count = storage.reduce(<span class="hljs-function">(<span class="hljs-params">counter, obj</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (obj.status === <span class="hljs-string">'0'</span>) counter += <span class="hljs-number">1</span>
  <span class="hljs-keyword">return</span> counter;
}, <span class="hljs-number">0</span>); <span class="hljs-comment">// 6</span>
</code></pre>
<p>You could simplify further by using ES6 syntax and a ternary operator:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storage = [
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'1'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'2'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'3'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'4'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'5'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'6'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'7'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'1'</span> },
];

<span class="hljs-keyword">const</span> count = storage.reduce(<span class="hljs-function">(<span class="hljs-params">counter, obj</span>) =&gt;</span> obj.status === <span class="hljs-string">'0'</span> ? counter += <span class="hljs-number">1</span> : counter, <span class="hljs-number">0</span>); <span class="hljs-comment">// 6</span>
</code></pre>
<p>And even a bit more by using <a target="_blank" href="https://www.freecodecamp.org/news/array-and-object-destructuring-in-javascript/">object destructuring</a>: </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storage = [
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'1'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'2'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'3'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'4'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'5'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'6'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'0'</span> },
  { <span class="hljs-attr">data</span>: <span class="hljs-string">'7'</span>, <span class="hljs-attr">status</span>: <span class="hljs-string">'1'</span> },
];

<span class="hljs-keyword">const</span> count = storage.reduce(<span class="hljs-function">(<span class="hljs-params">counter, { status }</span>) =&gt;</span> status === <span class="hljs-string">'0'</span> ? counter += <span class="hljs-number">1</span> : counter, <span class="hljs-number">0</span>); <span class="hljs-comment">// 6</span>
</code></pre>
<p>So those are a few ways to go through the elements of an array and count them conditionally. Now get out there and count with confidence!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Iterate Through Nested Object in React.js ]]>
                </title>
                <description>
                    <![CDATA[ If you've ever worked with APIs, you'll know that the structure of the data they return can get complicated quickly. Imagine you call an API from your React project and the response looks something like this: Object1 {      Object2 {      ]]>
                </description>
                <link>https://www.freecodecamp.org/news/iterate-through-nested-object-in-react-js/</link>
                <guid isPermaLink="false">66c358a27ef110ecbf367b27</guid>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 02 Jun 2020 02:17:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9aa2740569d1a4ca26c5.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've ever worked with APIs, you'll know that the structure of the data they return can get complicated quickly.</p>
<p>Imagine you call an API from your React project and the response looks something like this:</p>
<pre><code class="lang-json">Object1 {
     Object2 {
           propertyIWantToAcess:
           anotherpropertyIWantToAcess:
      }
}
</code></pre>
<p>You've stored the data within your component's state as <code>this.state.myPosts</code>, and can access the elements of the outer object with the following:</p>
<pre><code class="lang-jsx">render() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.state.myPosts);

    <span class="hljs-keyword">const</span> data = <span class="hljs-built_in">this</span>.state.myPosts;

    <span class="hljs-keyword">const</span> display = <span class="hljs-built_in">Object</span>.keys(data).map(<span class="hljs-function">(<span class="hljs-params">d, key</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"my-posts"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{key}</span>&gt;</span>
          {data.current_route}
        <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
      );
    });

    <span class="hljs-keyword">return</span>(
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
          { display }
        <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
</code></pre>
<p>But the problem is that you aren't able to access any of the inner objects.</p>
<p>The values of the inner objects will always change, so you aren't able to hardcode their keys and iterate through those to get the proper values.</p>
<h2 id="heading-possible-solutions">Possible solutions</h2>
<p>It can be difficult to work directly with complex API responses, so let's take a step back and simplify:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> visit = <span class="hljs-function">(<span class="hljs-params">obj, fn</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> values = <span class="hljs-built_in">Object</span>.values(obj)

    values.forEach(<span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> 
        val &amp;&amp; <span class="hljs-keyword">typeof</span> val === <span class="hljs-string">"object"</span> ? visit(val, fn) : fn(val))
}

<span class="hljs-comment">// Quick test</span>
<span class="hljs-keyword">const</span> print = <span class="hljs-function">(<span class="hljs-params">val</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(val)

<span class="hljs-keyword">const</span> person = {
    <span class="hljs-attr">name</span>: {
        <span class="hljs-attr">first</span>: <span class="hljs-string">"John"</span>,
        <span class="hljs-attr">last</span>: <span class="hljs-string">"Doe"</span>
    },
    <span class="hljs-attr">age</span>: <span class="hljs-number">15</span>,
    <span class="hljs-attr">secret</span>: {
        <span class="hljs-attr">secret2</span>: {
            <span class="hljs-attr">secret3</span>: {
                <span class="hljs-attr">val</span>: <span class="hljs-string">"I ate your cookie"</span>
            }
        }
    }
}

visit(person, print)
<span class="hljs-comment">/* Output
John
Doe
15
I ate your cookie
*/</span>
</code></pre>
<p>The <code>lodash</code> library has simple methods to accomplish the same thing, but this is a quick and dirty way to do the same thing in vanilla JS.</p>
<p>But say you want to simplify further, something like:</p>
<pre><code class="lang-jsx">render() {
    <span class="hljs-comment">// Logs data</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.state.myPosts);

    <span class="hljs-keyword">const</span> data = <span class="hljs-built_in">this</span>.state.myPosts;

    <span class="hljs-comment">// Stores nested object I want to access in posts variable</span>
    <span class="hljs-keyword">const</span> posts = data.content;

    <span class="hljs-comment">// Successfully logs nested object I want to access</span>
    <span class="hljs-built_in">console</span>.log(posts);

    <span class="hljs-comment">// Error, this will not allow me to pass posts variable to Object.keys</span>
    <span class="hljs-keyword">const</span> display = <span class="hljs-built_in">Object</span>.keys(posts).map(<span class="hljs-function"><span class="hljs-params">key</span> =&gt;</span>
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{key}</span>&gt;</span>{posts[key]}<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span></span>
    )


    <span class="hljs-keyword">return</span>(
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        {display}
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
 }
</code></pre>
<p>But you get an error, <code>TypeError: can't convert undefined to object error</code> whenever you try to pass <code>posts</code> to <code>Object.keys</code>.</p>
<p>Keep in mind that this error has nothing to do with React. It's illegal to pass an object as a child of a component.</p>
<p><code>Object.keys()</code> only returns the keys of the object that's passed in as a parameter. You'll need to call it multiple times to iterate through all the nested keys.</p>
<p>If you need to display the whole nested object, one option is to use a function to convert each object into a React component and pass it as an array:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> data= []

visit(obj, <span class="hljs-function">(<span class="hljs-params">val</span>) =&gt;</span> {
    data.push(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{val}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>)  <span class="hljs-comment">// wraps any non-object type inside &lt;p&gt;</span>
})
...
return &lt;SomeComponent&gt; {data} &lt;/SomeComponent&gt;
</code></pre>
<h2 id="heading-useful-packages">Useful packages</h2>
<p>Another option is to use a package like <a target="_blank" href="https://www.npmjs.com/package/json-query">json-query</a> to help iterate through the nested JSON data.</p>
<p>Here's a modified version of the <code>render</code> function above using <code>json-query</code>:</p>
<pre><code class="lang-jsx"> render() {
   <span class="hljs-keyword">const</span> utopian = <span class="hljs-built_in">Object</span>.keys(<span class="hljs-built_in">this</span>.state.utopianCash);
   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.state.utopianCash);

   <span class="hljs-keyword">var</span> author = jsonQuery(<span class="hljs-string">'[*][author]'</span>, { <span class="hljs-attr">data</span>: <span class="hljs-built_in">this</span>.state.utopianCash }).value
   <span class="hljs-keyword">var</span> title = jsonQuery(<span class="hljs-string">'[*][title]'</span>, { <span class="hljs-attr">data</span>: <span class="hljs-built_in">this</span>.state.utopianCash }).value
   <span class="hljs-keyword">var</span> payout = jsonQuery(<span class="hljs-string">'[*][total_payout_value]'</span>, { <span class="hljs-attr">data</span>: <span class="hljs-built_in">this</span>.state.utopianCash }).value
   <span class="hljs-keyword">var</span> postLink = jsonQuery(<span class="hljs-string">'[*][url]'</span>, { <span class="hljs-attr">data</span>: <span class="hljs-built_in">this</span>.state.utopianCash }).value
   <span class="hljs-keyword">var</span> pendingPayout = jsonQuery(<span class="hljs-string">'[*][pending_payout_value]'</span>, { <span class="hljs-attr">data</span>: <span class="hljs-built_in">this</span>.state.utopianCash }).value
   <span class="hljs-keyword">var</span> netVotes = jsonQuery(<span class="hljs-string">'[*][net_votes]'</span>, { <span class="hljs-attr">data</span>: <span class="hljs-built_in">this</span>.state.utopianCash }).value


   <span class="hljs-keyword">let</span> display = utopian.map(<span class="hljs-function">(<span class="hljs-params">post, i</span>) =&gt;</span> {
     <span class="hljs-keyword">return</span> (
       <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"utopian-items"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>Author: <span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span>
          {author[i]}
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>Title: <span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">{</span>`<span class="hljs-attr">https:</span>//<span class="hljs-attr">www.steemit.com</span>` + <span class="hljs-attr">postLink</span>[<span class="hljs-attr">i</span>]}&gt;</span>{title[i]}<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>Pending Payout: <span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span>
            {pendingPayout[i]}
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>Votes: <span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span>
          {netVotes[i]}
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
       <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
     );
   });

    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"utopian-container"</span>&gt;</span>
        {display}
        <span class="hljs-tag">&lt;<span class="hljs-name">User</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}
</code></pre>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Array of Objects Tutorial – How to Create, Update, and Loop Through Objects Using JS Array Methods ]]>
                </title>
                <description>
                    <![CDATA[ By Ondrej Polesny On average I work with JSON data 18 times a week. And I still need to google for specific ways to manipulate them almost every time. What if there was an ultimate guide that could always give you the answer? In this article, I'll sh... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-array-of-objects-tutorial-how-to-create-update-and-loop-through-objects-using-js-array-methods/</link>
                <guid isPermaLink="false">66d4609b230dff0166905859</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ loop ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 14 May 2020 11:48:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/05/js-tutorial-cover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ondrej Polesny</p>
<p>On average I work with JSON data 18 times a week. And I still need to google for specific ways to manipulate them almost every time. What if there was an ultimate guide that could always give you the answer?</p>
<p>In this article, I'll show you the basics of working with object arrays in JavaScript.</p>
<p>If you ever worked with a JSON structure, you've worked with JavaScript objects. Quite literally. JSON stands for JavaScript Object Notation. </p>
<p>Creating an object is as simple as this:</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"color"</span>: <span class="hljs-string">"purple"</span>,
  <span class="hljs-string">"type"</span>: <span class="hljs-string">"minivan"</span>,
  <span class="hljs-string">"registration"</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2012-02-03'</span>),
  <span class="hljs-string">"capacity"</span>: <span class="hljs-number">7</span>
}
</code></pre>
<p>This object represents a car. There can be many types and colors of cars, each object then represents a specific car.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/purple.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now, most of the time you get data like this from an external service. But sometimes you need to create objects and their arrays manually. Like I did when I was creating this e-shop:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/categories.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Considering each category list item looks like this in HTML:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/code.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I didn't want to have this code repeated 12 times, which would make it unmaintainable.</p>
<h2 id="heading-creating-an-array-of-objects">Creating an array of objects</h2>
<p>But let's get back to cars. Let's take a look at this set of cars:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/cars.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We can represent it as an array this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> cars = [
  {
    <span class="hljs-string">"color"</span>: <span class="hljs-string">"purple"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"minivan"</span>,
    <span class="hljs-string">"registration"</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2017-01-03'</span>),
    <span class="hljs-string">"capacity"</span>: <span class="hljs-number">7</span>
  },
  {
    <span class="hljs-string">"color"</span>: <span class="hljs-string">"red"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"station wagon"</span>,
    <span class="hljs-string">"registration"</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2018-03-03'</span>),
    <span class="hljs-string">"capacity"</span>: <span class="hljs-number">5</span>
  },
  {
    ...
  },
  ...
]
</code></pre>
<p>Arrays of objects don't stay the same all the time. We almost always need to manipulate them. So let's take a look at how we can add objects to an already existing array.</p>
<h3 id="heading-add-a-new-object-at-the-start-arrayunshift">Add a new object at the start - Array.unshift</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/beginning.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To add an object at the first position, use <code>Array.unshift</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> car = {
  <span class="hljs-string">"color"</span>: <span class="hljs-string">"red"</span>,
  <span class="hljs-string">"type"</span>: <span class="hljs-string">"cabrio"</span>,
  <span class="hljs-string">"registration"</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2016-05-02'</span>),
  <span class="hljs-string">"capacity"</span>: <span class="hljs-number">2</span>
}
cars.unshift(car);
</code></pre>
<h3 id="heading-add-a-new-object-at-the-end-arraypush">Add a new object at the end - Array.push</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/ending.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To add an object at the last position, use <code>Array.push</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> car = {
 <span class="hljs-string">"color"</span>: <span class="hljs-string">"red"</span>,
 <span class="hljs-string">"type"</span>: <span class="hljs-string">"cabrio"</span>,
 <span class="hljs-string">"registration"</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2016-05-02'</span>),
 <span class="hljs-string">"capacity"</span>: <span class="hljs-number">2</span>
}
cars.push(car);
</code></pre>
<h3 id="heading-add-a-new-object-in-the-middle-arraysplice">Add a new object in the middle - Array.splice</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/middle.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To add an object in the middle, use <code>Array.splice</code>. This function is very handy as it can also remove items. Watch out for its parameters:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Array</span>.splice(
  {index where to start},
  {how many items to remove},
  {items to add}
);
</code></pre>
<p>So if we want to add the red Volkswagen Cabrio on the fifth position, we'd use:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> car = {
  <span class="hljs-string">"color"</span>: <span class="hljs-string">"red"</span>,
  <span class="hljs-string">"type"</span>: <span class="hljs-string">"cabrio"</span>,
  <span class="hljs-string">"registration"</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2016-05-02'</span>),
  <span class="hljs-string">"capacity"</span>: <span class="hljs-number">2</span>
}
cars.splice(<span class="hljs-number">4</span>, <span class="hljs-number">0</span>, car);
</code></pre>
<h2 id="heading-looping-through-an-array-of-objects">Looping through an array of objects</h2>
<p>Let me ask you a question here: Why do you want to loop through an array of objects? The reason I'm asking is that the looping is almost never the primary cause of what we want to achieve. </p>
<p>JavaScript provides many functions that can solve your problem without actually implementing the logic in a general cycle. Let's take a look.</p>
<h3 id="heading-find-an-object-in-an-array-by-its-values-arrayfind">Find an object in an array by its values - Array.find</h3>
<p>Let's say we want to find a car that is red. We can use the function <code>Array.find</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/cars-colorred.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> car = cars.find(<span class="hljs-function"><span class="hljs-params">car</span> =&gt;</span> car.color === <span class="hljs-string">"red"</span>);
</code></pre>
<p>This function returns the first matching element:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(car);
<span class="hljs-comment">// output:</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">//   color: 'red',</span>
<span class="hljs-comment">//   type: 'station wagon',</span>
<span class="hljs-comment">//   registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',</span>
<span class="hljs-comment">//   capacity: 5</span>
<span class="hljs-comment">// }</span>
</code></pre>
<p>It's also possible to search for multiple values:</p>
<p><code>let car = cars.find(car =&gt; car.color === "red" &amp;&amp; car.type === "cabrio");</code></p>
<p>In that case we'll get the last car in the list.</p>
<h3 id="heading-get-multiple-items-from-an-array-that-match-a-condition-arrayfilter">Get multiple items from an array that match a condition - Array.filter</h3>
<p>The <code>Array.find</code> function returns only one object. If we want to get all red cars, we need to use <code>Array.filter</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/cars-colorred2.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> redCars = cars.filter(<span class="hljs-function"><span class="hljs-params">car</span> =&gt;</span> car.color === <span class="hljs-string">"red"</span>);
<span class="hljs-built_in">console</span>.log(redCars);
<span class="hljs-comment">// output:</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   {</span>
<span class="hljs-comment">//     color: 'red',</span>
<span class="hljs-comment">//     type: 'station wagon',</span>
<span class="hljs-comment">//     registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',</span>
<span class="hljs-comment">//     capacity: 5</span>
<span class="hljs-comment">//   },</span>
<span class="hljs-comment">//   {</span>
<span class="hljs-comment">//     color: 'red',</span>
<span class="hljs-comment">//     type: 'cabrio',</span>
<span class="hljs-comment">//     registration: 'Sat Mar 03 2012 01:00:00 GMT+0100 (GMT+01:00)',</span>
<span class="hljs-comment">//     capacity: 2</span>
<span class="hljs-comment">//   }</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<h3 id="heading-transform-objects-of-an-array-arraymap">Transform objects of an array - Array.map</h3>
<p>This is something we need very often. Transform an array of objects into an array of different objects. That's a job for <code>Array.map</code>. Let's say we want to classify our cars into three groups based on their size.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/cars-sizes.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sizes = cars.map(<span class="hljs-function"><span class="hljs-params">car</span> =&gt;</span> {
  <span class="hljs-keyword">if</span> (car.capacity &lt;= <span class="hljs-number">3</span>){
    <span class="hljs-keyword">return</span> <span class="hljs-string">"small"</span>;
  }
  <span class="hljs-keyword">if</span> (car.capacity &lt;= <span class="hljs-number">5</span>){
    <span class="hljs-keyword">return</span> <span class="hljs-string">"medium"</span>;
  }
  <span class="hljs-keyword">return</span> <span class="hljs-string">"large"</span>;
});
<span class="hljs-built_in">console</span>.log(sizes);
<span class="hljs-comment">// output:</span>
<span class="hljs-comment">// ['large','medium','medium', ..., 'small']</span>
</code></pre>
<p>It's also possible to create a new object if we need more values:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> carsProperties = cars.map(<span class="hljs-function"><span class="hljs-params">car</span> =&gt;</span> {
 <span class="hljs-keyword">let</span> properties = {
   <span class="hljs-string">"capacity"</span>: car.capacity,
   <span class="hljs-string">"size"</span>: <span class="hljs-string">"large"</span>
 };
 <span class="hljs-keyword">if</span> (car.capacity &lt;= <span class="hljs-number">5</span>){
   properties[<span class="hljs-string">'size'</span>] = <span class="hljs-string">"medium"</span>;
 }
 <span class="hljs-keyword">if</span> (car.capacity &lt;= <span class="hljs-number">3</span>){
   properties[<span class="hljs-string">'size'</span>] = <span class="hljs-string">"small"</span>;
 }
 <span class="hljs-keyword">return</span> properties;
});
<span class="hljs-built_in">console</span>.log(carsProperties);
<span class="hljs-comment">// output:</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   { capacity: 7, size: 'large' },</span>
<span class="hljs-comment">//   { capacity: 5, size: 'medium' },</span>
<span class="hljs-comment">//   { capacity: 5, size: 'medium' },</span>
<span class="hljs-comment">//   { capacity: 2, size: 'small' },</span>
<span class="hljs-comment">//   ...</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<h3 id="heading-add-a-property-to-every-object-of-an-array-arrayforeach">Add a property to every object of an array - Array.forEach</h3>
<p>But what if we want the car size too? In that case we can enhance the object for a new property <code>size</code>. This is a good use-case for the <code>Array.forEach</code> function.</p>
<pre><code class="lang-js">cars.forEach(<span class="hljs-function"><span class="hljs-params">car</span> =&gt;</span> {
 car[<span class="hljs-string">'size'</span>] = <span class="hljs-string">"large"</span>;
 <span class="hljs-keyword">if</span> (car.capacity &lt;= <span class="hljs-number">5</span>){
   car[<span class="hljs-string">'size'</span>] = <span class="hljs-string">"medium"</span>;
 }
 <span class="hljs-keyword">if</span> (car.capacity &lt;= <span class="hljs-number">3</span>){
   car[<span class="hljs-string">'size'</span>] = <span class="hljs-string">"small"</span>;
 }
});
</code></pre>
<h3 id="heading-sort-an-array-by-a-property-arraysort">Sort an array by a property - Array.sort</h3>
<p>When we're done with transforming the objects, we usually need to sort them one way or another. </p>
<p>Typically, the sorting is based on a value of a property every object has. We can use the <code>Array.sort</code> function, but we need to provide a function that defines the sorting mechanism. </p>
<p>Let's say we want to sort the cars based on their capacity in descending order.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/cars-sort.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sortedCars = cars.sort(<span class="hljs-function">(<span class="hljs-params">c1, c2</span>) =&gt;</span> (c1.capacity &lt; c2.capacity) ? <span class="hljs-number">1</span> : (c1.capacity &gt; c2.capacity) ? <span class="hljs-number">-1</span> : <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(sortedCars);
<span class="hljs-comment">// output:</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   {</span>
<span class="hljs-comment">//     color: 'purple',</span>
<span class="hljs-comment">//     type: 'minivan',</span>
<span class="hljs-comment">//     registration: 'Wed Feb 01 2017 00:00:00 GMT+0100 (GMT+01:00)',</span>
<span class="hljs-comment">//     capacity: 7</span>
<span class="hljs-comment">//   },</span>
<span class="hljs-comment">//   {</span>
<span class="hljs-comment">//     color: 'red',</span>
<span class="hljs-comment">//     type: 'station wagon',</span>
<span class="hljs-comment">//     registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',</span>
<span class="hljs-comment">//     capacity: 5</span>
<span class="hljs-comment">//   },</span>
<span class="hljs-comment">//   ...</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<p>The <code>Array.sort</code> compares two objects and puts the first object in the second place if the result of the sorting function is positive. So you can look at the sorting function as if it was a question: Should the first object be placed in second place?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/sort.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Make sure to always add the case for zero when the compared value of both objects is the same to avoid unnecessary swaps.</p>
<h3 id="heading-checking-if-objects-in-array-fulfill-a-condition-arrayevery-arrayincludes">Checking if objects in array fulfill a condition - Array.every, Array.includes</h3>
<p><code>Array.every</code> and <code>Array.some</code> come handy when we just need to check each object for a specific condition. </p>
<p>Do we have a red cabrio in the list of cars? Are all cars capable of transporting at least 4 people? Or more web-centric: Is there a specific product in the shopping cart?</p>
<pre><code class="lang-js">cars.some(<span class="hljs-function"><span class="hljs-params">car</span> =&gt;</span> car.color === <span class="hljs-string">"red"</span> &amp;&amp; car.type === <span class="hljs-string">"cabrio"</span>);
<span class="hljs-comment">// output: true</span>

cars.every(<span class="hljs-function"><span class="hljs-params">car</span> =&gt;</span> car.capacity &gt;= <span class="hljs-number">4</span>);
<span class="hljs-comment">// output: false</span>
</code></pre>
<p>You may remember the function <code>Array.includes</code> which is similar to <code>Array.some</code>, but works only for primitive types.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we went through the basic functions that help you create, manipulate, transform, and loop through arrays of objects. They should cover most cases you will stumble upon.</p>
<p>If you have a use-case that requires more advanced functionality, take a look at <a target="_blank" href="https://www.freecodecamp.org/news/data-structures-101-arrays-a-visual-introduction-for-beginners-7f013bcc355a/">this detailed guide to arrays</a> or visit the <a target="_blank" href="https://www.w3schools.com/Jsref/jsref_obj_array.asp">W3 schools reference</a>.</p>
<p>Or <a target="_blank" href="https://twitter.com/ondrabus">get in touch with me</a> and I will prepare another article :-)</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
