<?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[ immutability - 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[ immutability - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 27 May 2026 23:10:05 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/immutability/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Immutable JavaScript – How to Improve the Performance of Your JS Applications ]]>
                </title>
                <description>
                    <![CDATA[ Javascript has become a very popular programming language thanks to its growing use in frontend and backend development.  And as devs build JavaScript applications for different companies and organizations, the size and complexity of these applicatio... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/immutable-javascript-improve-application-performance/</link>
                <guid isPermaLink="false">66bc4c5c303bf450de87bc7c</guid>
                
                    <category>
                        <![CDATA[ immutability ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ performance ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Clinton Joy ]]>
                </dc:creator>
                <pubDate>Mon, 05 Feb 2024 15:09:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Screen-Shot-2024-02-01-at-11.16.23-AM.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Javascript has become a very popular programming language thanks to its growing use in frontend and backend development. </p>
<p>And as devs build JavaScript applications for different companies and organizations, the size and complexity of these applications can pose interesting performance challenges.</p>
<p>As developers, we seek to create applications that not only have high performance but also have an enhanced user experience. To do this, we must fully understand how immutability works in Javascript, as this is one factor that contributes a lot to achieving the enhanced performance we seek.</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-immutability-in-javascript">What is immutability in JavaScript?</a></li>
<li><a class="post-section-overview" href="#heading-benefits-of-immutability-in-applications">Benefits of Immutability in Applications</a></li>
<li><a class="post-section-overview" href="#heading-techniques-for-achieving-immutability">Techniques for Achieving Immutability</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-es6-features-for-immutability-spread-syntax-and-objectfreeze">How to Use ES6 Features for Immutability – Spread Syntax and <code>Object.freeze()</code></a></li>
<li><a class="post-section-overview" href="#heading-performance-optimization-through-immutability">Performance Optimization through Immutability</a></li>
<li><a class="post-section-overview" href="#heading-real-world-examples-of-companies-and-projects-benefiting-from-immutability">Real-World Examples of Companies and Projects Benefiting from Immutability</a></li>
<li><a class="post-section-overview" href="#heading-common-pitfalls-of-immutable-javascript">Common Pitfalls of Immutable JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-best-practices-for-overcoming-immutability-related-issues">Best Practices for Overcoming Immutability-Related Issues</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-immutability-in-javascript">What is Immutability in JavaScript?</h2>
<p>According to the Oxford English Learners Dictionary, immutability means "something that cannot be changed; that will never change," whereas on the other hand, we have mutability, which is the direct opposite of immutability and means something that can change.</p>
<p>If you want to grasp the full meaning of immutability, we have to differentiate it from mutability. Mutability, in JavaScript, refers to the ability to modify the value of a variable or a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures">data type</a>. Immutability, on the other hand, means that once a value is created, it cannot be changed. JavaScript differentiates data types by their default characters.</p>
<p>Primitive data types such as <code>strings</code>, <code>numbers</code>, <code>booleans</code>, and symbols are immutable, while reference data types such as <code>objects</code>, <code>arrays</code>, and <code>functions</code> are mutable. </p>
<p>To explain further, let's take a look at this simple example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person1 = <span class="hljs-number">10</span>;
person2 = person1
person2 = <span class="hljs-number">8</span>;

<span class="hljs-built_in">console</span>.log(person2) <span class="hljs-comment">// 8</span>
<span class="hljs-built_in">console</span>.log(person1) <span class="hljs-comment">// 10</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>On examining this example, it would seem as if <code>person1</code> was modified. But the variable <code>person1</code> was reassigned to take the value of <code>person2</code>. But when we check the value of <code>person1</code> in the console, we will notice that the value of <code>person1</code> remains unchanged.</p>
<p>This means that the <code>person2</code> variable is just a clone of the <code>person1</code> variable that has been reassigned, and the actual value of the <code>person1</code> variable was not modified. </p>
<p>On the other hand, if we were to try to do the same with a reference data type, here's what would happen:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> student1 = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Kevin"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">20</span>,
};

student2 = student1;

student2.name = <span class="hljs-string">"Paul"</span>;

<span class="hljs-built_in">console</span>.log(student1) <span class="hljs-comment">// {name: 'Paul', age: 20}</span>
<span class="hljs-built_in">console</span>.log(student2) <span class="hljs-comment">// {name: 'Paul', age: 20}</span>
</code></pre>
<p><img src="https://hackmd.io/_uploads/B1WcDwZDp.png" alt="Screen Shot 2023-12-21 at 9.21.34 AM" width="600" height="400" loading="lazy">
<em>Mutable data example</em></p>
<p>On close inspection, you'll notice that as we set <code>student2</code> to be equal to <code>student1</code> and reassign the value of <code>student2.name</code>, it also changes the value of <code>student1.name</code>. This means that the value of <code>student1</code> was not just reassigned but modified. This proves that reference data types are mutable.</p>
<h2 id="heading-benefits-of-immutability-in-applications">Benefits of Immutability in Applications</h2>
<p>You may already be wondering: Isn't it a good thing for your variable to be mutable rather than rigid? Though mutability comes with some perks, so does immutability. In this section, we will see the benefits of immutability in applications.</p>
<p>First of all, immutable data structures are more stable and predictable. They're immune to unexpected alterations, rendering the code more deterministic and less prone to unforeseen bugs or side effects, which is very useful in large-scale applications.</p>
<p>You also have fewer bugs and data races. Immutability eliminates the possibility of accidentally modifying data in place, which can lead to data races and concurrency issues. By preventing direct modifications, immutability promotes thread safety and ensures that data remains consistent across multiple threads or processes.</p>
<p>Memory management and optimization also improve with immutability. It improves memory utilization by enabling safe data structure sharing, eliminating concerns about unintended modifications. </p>
<p>While the idea of creating copies might seem counterintuitive in pursuit of immutability, it is balanced by the benefits of structural sharing, efficient garbage collection, and the design of data structures.</p>
<p>These elements work to ensure that, despite the initial creation of copies for immutability, the long-term memory optimization prevails. The utilization of structural sharing minimizes the need for complete data duplication, while efficient garbage collection promptly removes unused data structures, contributing to optimal memory usage over time. </p>
<p>This approach not only reduces memory overhead but also optimizes resource utilization, playing a crucial role in scaling applications efficiently.</p>
<p>And finally, immutability produces more effective testing and debugging. Immutable data simplifies testing and debugging by providing a stable and predictable environment. Since objects cannot be modified, tests can focus on specific behaviors without worrying about external changes. This makes it easier to isolate and fix bugs.</p>
<h2 id="heading-techniques-for-achieving-immutability">Techniques for Achieving Immutability</h2>
<p>You can achieve immutability in JavaScript in a lot of ways, from using a persistent data structure to using ES6 features such as <code>Object.freeze()</code>. This section seeks to explain these techniques for achieving immutability and how you can use them.</p>
<h3 id="heading-introduction-to-persistent-data-structures">Introduction to Persistent Data Structures</h3>
<p>Persistence in data structures refers to the ability to retain the previous version while accommodating changes. In traditional mutable data structures, alterations directly modify the existing data. But in <a target="_blank" href="https://en.wikipedia.org/wiki/Persistent_data_structure#1">persistent data structures</a>, any modification creates a new version of the structure, leaving the original intact.</p>
<p>This characteristic is what makes persistent data structures inherently immutable. This promotes code reliability, efficient memory utilization, and allows for concurrent operations.</p>
<p>JavaScript itself, as a language, does not inherently offer persistent data structures in its standard library. But libraries and frameworks in JavaScript, like <a target="_blank" href="https://immutable-js.com/">Immutable.js</a>, offer implementations of persistent data structures. </p>
<p>Immutable.js provides various persistent data structures, including:</p>
<ul>
<li>Persistent List</li>
<li>Persistent Maps &amp; Sets</li>
<li>Persistent Trees</li>
</ul>
<h3 id="heading-persistent-lists">Persistent Lists</h3>
<p>Persistent lists, like immutable linked lists, allow for efficient modifications by creating new versions while reusing the majority of the existing structure.<br>Let's consider this example:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ShoppingList</span> </span>{
  <span class="hljs-keyword">constructor</span>(item, next = null) {
    <span class="hljs-built_in">this</span>.item = item;
    <span class="hljs-built_in">this</span>.next = next;
  }

  addItem(newItem) {
    <span class="hljs-comment">// Create a copy of the list</span>
    <span class="hljs-keyword">const</span> copiedList = <span class="hljs-built_in">this</span>.copyList();
    <span class="hljs-comment">// Add the new item to the copied list</span>
    <span class="hljs-keyword">return</span> copiedList.addItemToCopy(newItem);
  }

  addItemToCopy(newItem) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ShoppingList(newItem, <span class="hljs-built_in">this</span>);
  }

  removeItem(itemToRemove) {
    <span class="hljs-comment">// Create a copy of the list</span>
    <span class="hljs-keyword">const</span> copiedList = <span class="hljs-built_in">this</span>.copyList();
    <span class="hljs-keyword">let</span> current = copiedList;
    <span class="hljs-keyword">let</span> previous = <span class="hljs-literal">null</span>;

    <span class="hljs-keyword">while</span> (current !== <span class="hljs-literal">null</span>) {
      <span class="hljs-keyword">if</span> (current.item === itemToRemove) {
        <span class="hljs-keyword">if</span> (previous === <span class="hljs-literal">null</span>) {
          <span class="hljs-keyword">return</span> current.next;
        } <span class="hljs-keyword">else</span> {
          previous.next = current.next;
          <span class="hljs-keyword">return</span> copiedList;
        }
      }
      previous = current;
      current = current.next;
    }
    <span class="hljs-keyword">return</span> copiedList;
  }

  copyList() {
    <span class="hljs-comment">// Create a copy of the list</span>
    <span class="hljs-keyword">let</span> current = <span class="hljs-built_in">this</span>;
    <span class="hljs-keyword">let</span> newList = <span class="hljs-literal">null</span>;
    <span class="hljs-keyword">let</span> newListTail = <span class="hljs-literal">null</span>;

    <span class="hljs-keyword">while</span> (current !== <span class="hljs-literal">null</span>) {
      <span class="hljs-keyword">if</span> (newList === <span class="hljs-literal">null</span>) {
        newList = <span class="hljs-keyword">new</span> ShoppingList(current.item);
        newListTail = newList;
      } <span class="hljs-keyword">else</span> {
        newListTail.next = <span class="hljs-keyword">new</span> ShoppingList(current.item);
        newListTail = newListTail.next;
      }
      current = current.next;
    }
    <span class="hljs-keyword">return</span> newList;
  }
}

<span class="hljs-comment">// Creating a persistent shopping list</span>
<span class="hljs-keyword">const</span> originalList = <span class="hljs-keyword">new</span> ShoppingList(<span class="hljs-string">"Milk"</span>).addItem(<span class="hljs-string">"Eggs"</span>).addItem(<span class="hljs-string">"Bread"</span>);
<span class="hljs-keyword">const</span> updatedList = originalList.addItem(<span class="hljs-string">"Butter"</span>).addItem(<span class="hljs-string">"Cheese"</span>);

<span class="hljs-comment">// Removing an item from the list</span>
<span class="hljs-keyword">const</span> removedItem = updatedList.removeItem(<span class="hljs-string">"Eggs"</span>);

<span class="hljs-comment">// Logging the original, updated, and list after removing an item</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Original List:"</span>);
<span class="hljs-built_in">console</span>.log(originalList);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"\nUpdated List:"</span>);
<span class="hljs-built_in">console</span>.log(updatedList);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"\nList after removing an item:"</span>);
<span class="hljs-built_in">console</span>.log(removedItem);
</code></pre>
<p>In our code above, we define a class called <code>ShoppingList</code> which we use as a representation of a persistent shopping list. This persistent shopping list is one that can be modified and added to over time.</p>
<p>We have a constructor <code>constructor(item, next = null)</code> which initializes a new list node with the specified item and an optional reference to the next node.</p>
<p>The <code>addItem(newItem)</code> method creates a copy of the current list, adds the new item to the copy, and returns the modified copy. This ensures that the original list remains unchanged. The private <code>addItemToCopy(newItem)</code> method appends the new item to the end of the copied list. It creates a new list node with the new item and links it to the end of the copied list.</p>
<p>Then we have the <code>removeItem(itemToRemove)</code> method which is used to create a copy of the current list. It then searches for the specified item to remove, and returns the modified copy. It handles the case of removing an item from the beginning or middle of the list.</p>
<p>The <code>copyList()</code> method recursively traverses the current list, creating new list nodes in the copied list and linking them together. It ensures that the copied list accurately represents the original list.</p>
<p>This example demonstrates using the ShoppingList class to create a persistent shopping list. It starts with an initial list of "Milk", "Eggs", and "Bread", adds "Butter" and "Cheese", and then removes "Eggs".</p>
<p>Here is the result of our code:</p>
<p><img src="https://hackmd.io/_uploads/r1Uk3SNup.png" alt="Screen Shot 2024-01-04 at 5.16.10 PM" width="600" height="400" loading="lazy"></p>
<p><img src="https://hackmd.io/_uploads/Byf9CH4_p.png" alt="Screen Shot 2024-01-04 at 5.27.59 PM" width="600" height="400" loading="lazy">
<em>Persistent list Example</em></p>
<p>As you can see, despite updating the list, the original list still retains its original data and can be accessed.</p>
<h3 id="heading-persistent-maps-and-sets">Persistent Maps and Sets</h3>
<p>Persistent maps and sets retain their previous versions when modified, offering efficient key-value pair storage or unique value collections with immutability.<br>Let's consider this example:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TreasureChest</span> </span>{
  <span class="hljs-keyword">constructor</span>(contents = {}) {
    <span class="hljs-built_in">this</span>.contents = { ...contents };
  }

  addTreasure(key, value) {
    <span class="hljs-keyword">const</span> newContents = { ...this.contents, [key]: value };
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> TreasureChest(newContents);
  }
}

<span class="hljs-comment">// Creating a persistent treasure chest (map-like)</span>
<span class="hljs-keyword">const</span> originalChest = <span class="hljs-keyword">new</span> TreasureChest({ <span class="hljs-attr">gold</span>: <span class="hljs-number">100</span>, <span class="hljs-attr">gems</span>: <span class="hljs-number">5</span> });
<span class="hljs-keyword">const</span> updatedChest = originalChest.addTreasure(<span class="hljs-string">"diamonds"</span>, <span class="hljs-number">10</span>);

<span class="hljs-comment">// Logging the original and updated chests</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Original Chest:"</span>);
<span class="hljs-built_in">console</span>.log(originalChest);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"\nUpdated Chest:"</span>);
<span class="hljs-built_in">console</span>.log(updatedChest);
</code></pre>
<p>Above, we have a real-world code example. I like to call her Treasure Chest. In the code, we define a class called <code>TreasureChest</code> to represent a treasure chest that holds various items. The constructor method initializes the treasure chest with an optional contents object, which represents the initial items in the chest. If no contents object is provided, an empty object is used.</p>
<p>The <code>addTreasure</code> method adds a new item to the treasure chest. It takes two arguments: the name of the item (<code>key</code>) and the quantity (<code>value</code>). It creates a new contents object by merging the current contents with a new entry for the specified item, ensuring that the new item is added without modifying the original contents. It then creates a new <code>TreasureChest</code> object using the updated contents and returns it.</p>
<p>From the code, you can see we created two instances for the <code>TreasureChest</code> class. First the <code>originalChest</code> and then the <code>updatedChest</code>. <code>originalChest</code> is initialized with { <code>gold: 100, gems: 5</code> }, representing a chest with 100 gold coins and 5 gems. <code>updatedChest</code> is created using <code>originalChest.addTreasure('diamonds', 10)</code>, adding 10 diamonds to the chest.  </p>
<p><img src="https://hackmd.io/_uploads/HyU7JIVua.png" alt="Screen Shot 2024-01-04 at 5.30.27 PM" width="600" height="400" loading="lazy">
<em>Persistent Maps and Sets Example</em></p>
<p>From our console, we can confirm that this immutability technique works as our original Chest value is retrieved.</p>
<h3 id="heading-persistent-trees">Persistent Trees</h3>
<p>Persistent trees, such as binary trees or trie structures, are yet another technique for achieving immutability. They maintain previous versions during operations like insertion, deletion, or search. They create new tree instances upon modifications while reusing unchanged parts from the original tree.</p>
<p>This preservation of versions enables efficient manipulation and retrieval of data without mutating the original tree. Aside from immutability, a persistent tree also has some key characteristics, such as shared structure and efficient modifications.</p>
<p>These two features let us share unchanged parts between versions of our tree and enable efficient operations (such as insertion, deletion, or traversal) by reusing existing nodes and creating new branches only when necessary, respectively.<br>Here is an example:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TreeNode</span> </span>{
  <span class="hljs-keyword">constructor</span>(value, left = null, right = null) {
    <span class="hljs-built_in">this</span>.value = value;
    <span class="hljs-built_in">this</span>.left = left;
    <span class="hljs-built_in">this</span>.right = right;
  }

  insert(newValue) {
    <span class="hljs-keyword">if</span> (newValue &lt; <span class="hljs-built_in">this</span>.value) {
      <span class="hljs-comment">// Insert to the left</span>
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> TreeNode(
        <span class="hljs-built_in">this</span>.value,
        <span class="hljs-built_in">this</span>.left ? <span class="hljs-built_in">this</span>.left.insert(newValue) : <span class="hljs-keyword">new</span> TreeNode(newValue),
        <span class="hljs-built_in">this</span>.right
      );
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-comment">// Insert to the right</span>
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> TreeNode(
        <span class="hljs-built_in">this</span>.value,
        <span class="hljs-built_in">this</span>.left,
        <span class="hljs-built_in">this</span>.right ? <span class="hljs-built_in">this</span>.right.insert(newValue) : <span class="hljs-keyword">new</span> TreeNode(newValue)
      );
    }
  }
}

<span class="hljs-comment">// Creating a simplified tree structure</span>
<span class="hljs-keyword">const</span> root = <span class="hljs-keyword">new</span> TreeNode(<span class="hljs-number">5</span>);
root.left = <span class="hljs-keyword">new</span> TreeNode(<span class="hljs-number">3</span>);
root.right = <span class="hljs-keyword">new</span> TreeNode(<span class="hljs-number">8</span>);

<span class="hljs-comment">// Logging the original tree</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Original Tree:"</span>);
<span class="hljs-built_in">console</span>.log(root);

<span class="hljs-comment">// Creating an updated tree by inserting a new value (in this case, 10)</span>
<span class="hljs-keyword">const</span> updatedRoot = root.insert(<span class="hljs-number">10</span>);

<span class="hljs-comment">// Logging the updated tree</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"\nUpdated Tree:"</span>);
<span class="hljs-built_in">console</span>.log(updatedRoot);
</code></pre>
<p>In the code above, we focused on creating and modifying a <code>TreeNode</code>. We defined a <code>TreeNode</code> class that represents a node in a binary tree. A binary tree is a hierarchical data structure where each node can have up to two child nodes, referred to as the left child and the right child.</p>
<p>Our <code>TreeNode</code> class has two constructors: the default constructor, which creates a node with the specified value, and two child nodes, which can also be null. The left and right properties represent the left and right child nodes, respectively.</p>
<p>The <code>TreeNode</code> class also has the insert method, which is used to insert a new value into the tree. The method takes a single argument, which is the value to be inserted.</p>
<p>The insert method first compares the new value to the value of the current node. If the new value is less than the value of the current node, it is inserted to the left of the current node. If the new value is greater than the value of the current node, it is inserted to the right of the current node.</p>
<p>If the current node does not have a child node corresponding to the insertion direction, a new node is created and inserted as the child node. If the current node already has a child node in that direction, the insertion method is recursively called on that child node to handle the insertion.</p>
<p>The code then creates a simplified tree structure with the root node having value 5, a left child node with value 3, and a right child node with value 8. Later on, we insert a new value of 10 into the tree using the insert method of the root node.</p>
<p><img src="https://hackmd.io/_uploads/SkQ2yLEOa.png" alt="Screen Shot 2024-01-04 at 5.32.43 PM" width="600" height="400" loading="lazy">
<em>Persistent Tree Example</em></p>
<h2 id="heading-how-to-use-es6-features-for-immutability-spread-syntax-and-objectfreeze">How to Use ES6 Features for Immutability – Spread Syntax and <code>Object.freeze()</code></h2>
<p>At the start of this tutorial, I explained the difference between mutable and immutable data types, and we saw some examples illustrating how they work. </p>
<p>Mutable data types such as arrays and objects are still super useful, and through the use of some ES6 features such as the spread operator and <code>Object.freeze</code>, we can utilize data types like arrays and objects while maintaining a degree of immutability.</p>
<h3 id="heading-the-spread-syntax">The Spread Syntax</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spread operator (…)</a> in JavaScript is a powerful tool that facilitates the creation of shallow copies of arrays, objects, and iterables. When it comes to immutability, the spread operator plays a crucial role in ensuring that the original data remains unchanged while allowing the creation of new, independent data structures.</p>
<p>Let's consider an array in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> originalArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
</code></pre>
<p>Using the spread operator, you can create an immutable copy of this array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> immutableCopy = [...originalArray];
</code></pre>
<p>Here, <code>immutableCopy</code> holds a new array with the same elements as <code>originalArray</code>. Any modifications to <code>immutableCopy</code> won't affect <code>originalArray</code>, ensuring the immutability of the original data. This technique has been adopted by a lot of developers in modern-day software development.</p>
<h3 id="heading-the-objectfreeze-method">The <code>Object.freeze()</code> method</h3>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze"><code>Object.freeze()</code></a> is a method that can be used on reference data types. It prevents any form of modification or addition to an object, thereby creating an object with a read-only type.</p>
<p>Let's consider this example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating an immutable object using Object.freeze()</span>
<span class="hljs-keyword">const</span> originalObj = { <span class="hljs-attr">name</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> };
<span class="hljs-keyword">const</span> immutableObj = <span class="hljs-built_in">Object</span>.freeze(originalObj); <span class="hljs-comment">// Freezes the object</span>

<span class="hljs-comment">// Attempting to modify a frozen object (in strict mode)</span>
immutableObj.age = <span class="hljs-number">30</span>; <span class="hljs-comment">// This change will not take effect (in strict mode)</span>
<span class="hljs-built_in">console</span>.log(originalObj);
<span class="hljs-built_in">console</span>.log(immutableObj);
</code></pre>
<p>In the code, the <code>originalObj</code> is a simple object with two properties: <code>name</code> and <code>age</code>. The <code>immutableObj</code> is created by calling <code>Object.freeze(originalObj)</code>. This effectively freezes the <code>originalObj</code>, preventing any further modifications to its properties.</p>
<p>We then try to code to modify the <code>immutableObj</code> by changing its age property to 30. However, since the object is frozen, this change will not take effect. In strict mode, attempting to modify a frozen object will result in a type error.</p>
<p><img src="https://hackmd.io/_uploads/r16WDjNvp.png" alt="Screen Shot 2023-12-23 at 8.29.17 PM" width="600" height="400" loading="lazy"></p>
<p>Without strict mode, the <code>immutableObj</code> object remains immutable.</p>
<p><img src="https://hackmd.io/_uploads/ByKYwjNwT.png" alt="Screen Shot 2023-12-23 at 8.30.34 PM" width="600" height="400" loading="lazy">
<em>Object.freeze for javaScript immutability.</em></p>
<h2 id="heading-performance-optimization-through-immutability">Performance Optimization through Immutability</h2>
<p>Immutability, unchangeability—you might wonder, does this cause more harm than good? Well, let's see.</p>
<p>Let's consider a few more steps in the process, like safeguarding your data. These steps are an investment in stability and predictability.</p>
<p>In mutable structures, whenever data changes, it involves copying or altering existing data, which can get messy, especially in large-scale applications.</p>
<p>When you're dealing with tons of data and constantly modifying it in a mutable structure, your code has to keep track of those changes. This constant tracking and altering can add up, leading to higher computational costs.</p>
<p>On the other hand, with immutable data, once created, it stays put. This means fewer surprises and less overhead in managing changes.</p>
<h3 id="heading-comparison-of-mutable-vs-immutable-data">Comparison of mutable vs. immutable data</h3>
<p>When comparing mutable and immutable data structures in large-scale applications, it's essential to highlight the fundamental differences that affect performance, memory usage, and overall stability.</p>
<p>Here's a breakdown in a more technical manner:</p>
<table><thead><tr><th><span>Aspect</span></th><th><span>Mutablility</span></th><th><span>Immutability</span></th></tr></thead><tbody><tr><td><span>Memory Management</span></td><td><span>Tend to require more memory due to in-place modifications.</span></td><td><span>Often use memory more efficiently by creating new instances.</span></td></tr><tr><td><span>Concurrent Access</span></td><td><span>Prone to issues with concurrent access (race conditions).</span></td><td><span>Safe for concurrent access as data doesn't change.</span></td></tr><tr><td><span>Error-Prone</span></td><td><span>Mutable states can lead to unintended bugs and errors.</span></td><td><span>Immutable structures minimize unintended side effects, reducing errors.</span></td></tr><tr><td><span>Ease of Reasoning and Debugging</span></td><td><span>Tracking changes can be complex, making debugging harder.</span></td><td><span>Easier to reason about as data remains consistent. Debugging is more straightforward.</span></td></tr><tr><td><span>Scalability</span></td><td><span>Can pose challenges in managing state changes at scale.</span></td><td><span>Facilitate scalability due to predictable and consistent data.</span></td></tr></tbody></table>

<p>As you can see from the table, there is a lot to benefit from adopting immutability.</p>
<h2 id="heading-real-world-examples-of-companies-and-projects-benefiting-from-immutability">Real-World Examples of Companies and Projects Benefiting from Immutability</h2>
<p>Immutability in programming is a concept that has several advantages, and several companies and projects have benefited from it. Some of the companies are Facebook, Github, Netflix, WhatsApp, and Uber.</p>
<p>React, a Facebook library, uses immutability as a major principle, providing improved performance and responsiveness. Github, a collaborative tool, also makes use of React in its user interface, thereby benefiting from immutability. Netflix, WhatsApp, and Uber also benefit from immutability by making use of immutable data structures to produce consistent and reliable applications.</p>
<p>These are a few of the many examples of companies benefiting from immutability.</p>
<h2 id="heading-common-pitfalls-of-immutable-javascript">Common Pitfalls of Immutable JavaScript</h2>
<p>Although immutability has its advantages, it can also be quite challenging if you don't use it properly. Most of the time, many beneficial things come with a cost.</p>
<p>Immutability may cause a decrease in performance if used on large datasets, because new data structures are created instead of modifying existing ones.<br>Also totally learning the immutable approach to programming can be quite tasking, since it may involve learning how to use new libraries and techniques. But it's definitely worth it.</p>
<p>Since immutability works hand in hand with functional programming, it's also a good idea for someone implementing immutability to learn functional programming.</p>
<h3 id="heading-data-races-and-concurrency-issues">Data races and concurrency issues</h3>
<p>When working with immutable data, data races and concurrency issues can still be potential issues. Some of these issues relate to shared reference, asynchronous operations, and state management.</p>
<p>While the data itself might be immutable, references to that data can still be shared among different parts of the code. And if multiple parts of the codebase hold references to the same immutable data and one of them attempts to modify it (even though it can't change the original data), it can cause unintended consequences or unexpected behavior elsewhere in the code that relies on the unchanged data.</p>
<p>In JavaScript, asynchronous operations can introduce concurrency issues. Even though JavaScript is single-threaded, asynchronous functions (like fetching data from APIs or handling events) can create scenarios where different parts of the code operate at different times. </p>
<p>If these asynchronous operations involve shared state, even with immutable data, managing the changes or handling the state updates can lead to unexpected behavior or bugs.</p>
<p>While immutability helps in maintaining predictable state changes, managing the state across an application can still be a challenge. Libraries like Redux in React applications, for instance, rely heavily on immutable data principles to manage state changes effectively. But improper handling of state updates or mutations within such libraries can lead to unexpected behavior.</p>
<h2 id="heading-best-practices-for-overcoming-immutability-related-issues">Best Practices for Overcoming Immutability-Related Issues</h2>
<p>Since immutability can pose some challenges, especially when used in a large-scale applications, it's a good idea to learn ways that we can overcome these challenges.</p>
<ul>
<li>Selective usage: To avoid decreased performance in your projects, you can choose where to use immutable data. Since immutability relies on creating new datasets instead of modifying them, you should use it in parts of your projects that do not require high performance.</li>
<li>Avoid deep cloning: Deep clones of data structures can be resource-intensive, so it's best to make use of shallow or partial updates if they can also provide the same results for you.</li>
<li>Implement Copy-on-Write strategy: The creation of new copies of data should only be used when you need data in a data structure to be modified. This can reduce copies that could be avoided, thereby increasing performance.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The benefits of leveraging immutability in your applications are clear. Immutability serves as a powerful tool that can help you reduce bugs, improve responsiveness, and prevent unnecessary re-renders. </p>
<p>It may still pose some challenges, but through practicing the right strategies, you can handle them and use them to develop very high-quality as well as cost-effective applications.</p>
<p>Immutability remains an essential component of the optimization and responsiveness of large-scale applications being built in the JavaScript community, an area where JavaScript is still growing.</p>
<p>As a developer, learning to apply the immutable method of programming will go a long way toward optimizing most of your projects and reducing the occurrence of bugs and errors. Learning this method of programming would be an investment that yields long-term benefits.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Immutability in JavaScript – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Deborah Kurata We often hear the terms: immutable and immutability. But what do they mean, and, as developers, why should we care? Immutable basically means something that cannot be changed. In programming, immutable is used to describe a value th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/immutability-in-javascript-with-examples/</link>
                <guid isPermaLink="false">66d45e08d1ffc3d3eb89ddbb</guid>
                
                    <category>
                        <![CDATA[ immutability ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jan 2024 23:21:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/thumbnail.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Deborah Kurata</p>
<p>We often hear the terms: <strong>immutable</strong> and <strong>immutability</strong>. But what do they mean, and, as developers, why should we care?</p>
<p>Immutable basically means something that cannot be changed. In programming, immutable is used to describe a value that cannot be changed after it's been set.</p>
<p>But, most programs require creating, updating, and deleting data. So why would we ever want to work with data that can't be changed?</p>
<p>In this tutorial, we'll look at immutability of primitives, arrays, and objects with JavaScript examples. And I'll explain why immutability is important for programming.</p>
<p>You can also watch the associated video here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/DBZESPS-5mQ" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>And here is a JavaScript example (which you can <a target="_blank" href="https://stackblitz.com/edit/immutability-deborahk?file=index.js">also view on Stackblitz</a>):</p>
<pre><code class="lang-js"><span class="hljs-comment">// Import stylesheets</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./style.css'</span>;

<span class="hljs-comment">// Write JavaScript code!</span>
<span class="hljs-keyword">const</span> appDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'app'</span>);
appDiv.innerHTML = <span class="hljs-string">`&lt;h1&gt;Open the console to see results&lt;/h1&gt;`</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-comment">//_name = "Nee";</span>
  <span class="hljs-comment">//_name = ["Nee", "Ra"];</span>
  _name = { <span class="hljs-attr">first</span>: <span class="hljs-string">"Nee"</span>, <span class="hljs-attr">middle</span>: <span class="hljs-string">"L"</span> };

  <span class="hljs-keyword">get</span> <span class="hljs-title">name</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._name;
  }

  <span class="hljs-keyword">set</span> <span class="hljs-title">name</span>(<span class="hljs-params">value</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'In setter'</span>, value);
    <span class="hljs-built_in">this</span>._name = value;
  }
}

<span class="hljs-keyword">let</span> p = <span class="hljs-keyword">new</span> Person();
<span class="hljs-comment">//p.name = "Ra";                        // Setter executes</span>
<span class="hljs-comment">//p.name.push("Lee");                   // Setter doesn't execute</span>
<span class="hljs-comment">//p.name = [...p.name, "Lee"];          // Setter executes</span>
<span class="hljs-comment">//p.name.middle = "Lee";                // Setter doesn't execute</span>
p.name = { ...p.name, <span class="hljs-attr">middle</span>: <span class="hljs-string">"Lee"</span> };  <span class="hljs-comment">// Setter executes</span>
</code></pre>
<p>Let's start with primitives.</p>
<h2 id="heading-primitives-in-javascript-naturally-immutable">Primitives in JavaScript: Naturally Immutable</h2>
<p>In JavaScript, primitives, like strings and numbers, are immutable by default. This means that once a primitive value is created, it can't be changed. Wait a minute, you might think – I change primitive variable values all the time!</p>
<p>Well, it might seem like you're modifying a value. But that's not actually the case. Here's an example.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> greet = <span class="hljs-string">"Hello"</span>;
greet += <span class="hljs-string">", World"</span>;  
<span class="hljs-built_in">console</span>.log(greet);
</code></pre>
<p>The first line of this code creates the string <code>Hello</code> and assigns it to the <code>greet</code> variable. The second line appends <code>, World</code> to that string. So it looks like we're changing the <code>greet</code> string. But JavaScript does not change the string. Rather, it creates a new string.</p>
<p>Let's look at an illustration. Here we have a <code>greet</code> variable assigned to the <code>Hello</code> string.</p>
<p><img src="https://lh7-us.googleusercontent.com/9-7QkMgYxQdlMMreWAQywiB3yy4k7xi8WkfWNeP0dbDANyNCpUVulbPOsVD06EDGLuZKH4MK_8prwlIqqV0eRVI8BrH3VV8hE7nlxH2zsVg6Fw0HSqe_TN26vGgm_99pmlWKaqGqFU1xy6t0DjpRzMg" alt="Image" width="1230" height="764" loading="lazy">
<em>Figure 1. The code creates the string <code>Hello</code> and assigns it to the <code>greet</code> variable.</em></p>
<p>When the code appends text, JavaScript creates a new string. It then assigns the <code>greet</code> variable to this new string. The original <code>Hello</code> string is not modified.</p>
<p><img src="https://lh7-us.googleusercontent.com/T_KgVb_6Cy-rBP7bnxQUaosHDaFbvfh2MY8XNrEvsM0rJDgx7Qih1sH6OYL9qBLqlBIM3bNiKQ1jJKeM5UwQSurqkUr-MBztWjkFZbxtYgCL_V8PjfBhO4mYd_4lzym2xwtXjPpZ8p9cHzcCVGNuHXg" alt="Image" width="1230" height="802" loading="lazy">
<em>Figure 2. Appending text creates a new string and assigns it to the <code>greet</code> variable.</em></p>
<p>So strings and other primitives are immutable by default in JavaScript.</p>
<p>How about arrays?</p>
<h2 id="heading-javascript-arrays-are-mutable">JavaScript Arrays are Mutable</h2>
<p>In JavaScript, arrays are mutable by default. This means that the array can be altered after the array is created. We can modify it "in place", adding, removing, or changing elements.</p>
<p>Let's look at an example.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> ages = [<span class="hljs-number">42</span>, <span class="hljs-number">22</span>, <span class="hljs-number">35</span>];
ages.push(<span class="hljs-number">8</span>);  
<span class="hljs-built_in">console</span>.log(ages);
</code></pre>
<p>The first line of code defines an array and assigns a variable to that array. But in JavaScript, the variable doesn't store the array. It stores the memory address where the array resides, as illustrated in Figure 3 here:</p>
<p><img src="https://lh7-us.googleusercontent.com/v7dmTur_H7PetKYQkvHGbjYPKWaZhkevFhgHO8gJxufnHN24p_h4gkAupNbqX9SqvLhjw8KFuuwSwWTMJocMX4t-D0r0vwRr6mvf-2G--SwSSuBi1mfqC31kUFzudwCB1qUJnqGPM7YDsWozqg0ZfDg" alt="Image" width="1312" height="730" loading="lazy">
<em>Figure 3. A variable doesn't store an array – it stores the memory address of the array.</em></p>
<p>In the second line of code in the prior example, we use the <code>push</code> method to modify the original array. In this case, we add 8 to the end of the array. This is shown in Figure 4:</p>
<p><img src="https://lh7-us.googleusercontent.com/TCWSxZMXMh5Oz06HncXSt5OapytcOfTRKdwCAAM3mac6XFndE6p_VpMkjkQAvUqxlTdpLwQaRorROsXCIcif8KJPtQmGKY7rbSQVad_QXAJ04AIyfY3Gn28cAeO2wHPSNcv4MN0KueD1AjmhKgrzYoM" alt="Image" width="1306" height="722" loading="lazy">
<em>Figure 4. A JavaScript array is changed "in place".</em></p>
<p>Notice that the memory address of the array doesn't change, but the array itself does change. So the array value is mutable.</p>
<p>This mutability provides flexibility. But mutability can lead to unintended side-effects, especially in larger applications or those involving concurrent operations.</p>
<p>And mutability has issues. Say you have code in a setter that should execute when the array is changed. Or you're working with a framework, such as Angular, that provides change detection. Or you're using a state library, such as Redux, that requires immutability.</p>
<p>As we saw in this example our array is changed...but our <code>ages</code> variable didn't actually change, since it's referencing the memory address. So the setter or change detection or state management might not be aware that the array was changed.</p>
<p>To avoid these pitfalls of mutability, we, as JavaScript developers, often use patterns or methods that do not alter the original array but instead return a new array. This embraces immutability.</p>
<h2 id="heading-how-to-embrace-immutability-with-arrays">How to Embrace Immutability with Arrays</h2>
<p>Let's look at an alternate example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> ages = [<span class="hljs-number">42</span>, <span class="hljs-number">22</span>, <span class="hljs-number">35</span>];
ages = [...ages, <span class="hljs-number">8</span>];  
<span class="hljs-built_in">console</span>.log(ages);
</code></pre>
<p>In this code, we start with the same array. But when we add an element, we use the JavaScript spread operator. The spread operator makes a copy of the existing array at a new address by "spreading" the existing array.</p>
<p>We then add the new element to that copy. We also reassign the <code>ages</code> variable to the address of the new array (Figure 5).</p>
<p><img src="https://lh7-us.googleusercontent.com/3zRss4le02LtJWuvVAodTOv6lGDWGBkoZ6LvluPSojWfkEDWU3n6R-PAktzUMd92Ua9sNzc-kuFis6u2xOFsUkKCjxR8SdPY4-4x43hP8Wp13CbA5XHE-aXBtq2VjMPGdMXtE_XaZbDTuiWzRHGGYaQ" alt="Image" width="1314" height="1350" loading="lazy">
<em>Figure 5. Using the spread operator, we create a new array at a new address and assign it to the <code>ages</code> variable.</em></p>
<p>Notice that the original array is not changed. By using the spread operator, we achieve immutability.</p>
<p>In addition to the spread operator, many of the array methods also create a new array and therefore treat an array as immutable. Other array methods modify the array in place and are therefore mutable. Here are some examples.</p>
<ul>
<li><code>Map</code> creates a new array from the existing array, mapping each element using a function we provide. It leaves the original array unchanged. So it supports immutability.</li>
</ul>
<pre><code class="lang-javascript">ages.map(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x + <span class="hljs-number">1</span>);
</code></pre>
<ul>
<li><code>Push</code> modifies the original array in place, mutating the array.</li>
</ul>
<pre><code class="lang-javascript">ages.push(<span class="hljs-number">8</span>);
</code></pre>
<ul>
<li><code>Filter</code> creates a new array with items matching the defined criteria. It leaves the original array unchanged.</li>
</ul>
<pre><code class="lang-javascript">ages.filter(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x &gt; <span class="hljs-number">21</span>);
</code></pre>
<ul>
<li><code>Sort</code> sorts the array elements in place, thereby mutating the array.</li>
</ul>
<pre><code class="lang-javascript">ages.sort();
</code></pre>
<ul>
<li><code>Slice</code> creates a new array from a portion of an existing array. Here we copy the original array elements starting at index 1 through index 3 to a new array.</li>
</ul>
<pre><code class="lang-javascript">ages.slice(<span class="hljs-number">1</span>, <span class="hljs-number">3</span>);
</code></pre>
<ul>
<li><code>Splice</code> changes the contents of an array in place, adding, removing, or replacing existing elements. In this example, the code starts replacing elements at index 2, only replaces 1 element, and replaces the element with "18".</li>
</ul>
<pre><code class="lang-javascript">ages.splice(<span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">18</span>);
</code></pre>
<p>So even though by default arrays are mutable, we can use immutability techniques to better manage our arrays.</p>
<p>What about objects?</p>
<h2 id="heading-the-mutable-nature-of-javascript-objects">The Mutable Nature of JavaScript Objects</h2>
<p>Objects in JavaScript are also mutable by default. We can add or delete properties and change property values "in place" after an object is created.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> p = {<span class="hljs-attr">name</span>:<span class="hljs-string">"Nee"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>};
p.age = <span class="hljs-number">31</span>;
<span class="hljs-built_in">console</span>.log(p);
</code></pre>
<p>The first line of this code example declares a person object with name and age properties. When a variable is assigned to that object, the variable doesn't store the object, but rather a memory address where the object resides.</p>
<p><img src="https://lh7-us.googleusercontent.com/-z8t2kPHCLlKG5y2D8p37azjtcc-a-Na_JarvtrXgTHbcsCjpZd3pYPxSdA5NAtTfNNllVXevr71jfV6X9UymACPkr-WyeQAwi-Auc32G4q9H8WEOlm-S4c_CbEzV5FhLIjq8btJAsUr35m5wclTmtI" alt="Image" width="1334" height="730" loading="lazy">
<em>Figure 6. A variable doesn't store an object. Rather, it stores the memory address of the object.</em></p>
<p>The second line of code in the prior example modifies the value of an object property, changing the age. This modification directly alters the original person object.</p>
<p><img src="https://lh7-us.googleusercontent.com/1OBvr491s67DqK4M3poTs31M5yjB2tQK9vo9QiWpLSSB-iSkC1qNKoypVC-Zhiitn56jMgfP_khoSNneCoPNJa9tp71Z3OSvgCl-jO15yaqGejOSa0WhL6VoapluQxjnxZ8SVluWcoe203m9t2nSdmU" alt="Image" width="1292" height="752" loading="lazy">
<em>Figure 7. A JavaScript object is changed "in place".</em></p>
<p>Notice that the memory address of the object doesn't change, but the object itself changes. This is similar to array mutability, and that makes sense because arrays in JavaScript are basically objects.</p>
<p>Mutability provides flexibility but can lead to complex bugs if not carefully managed.</p>
<p>And as with an array, mutability has issues. Say you have code in a setter that should execute when the object changes. Or you're working with a framework, such as Angular, that provides change detection. Or you're using a state library, such as Redux, that requires immutability.</p>
<p>In this example, our object changed but our <code>p</code> variable didn't actually change, since it's referencing the memory address. So the setter or change detection or state management may not see that the object was changed.</p>
<p>It's often better to handle objects in an immutable manner. JavaScript provides features to aid with immutable objects.</p>
<h2 id="heading-immutability-with-objects">Immutability with Objects</h2>
<p>Here is an alternate example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> p = {<span class="hljs-attr">name</span>:<span class="hljs-string">"Nee"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>};
p = {...p, <span class="hljs-attr">age</span>: <span class="hljs-number">31</span>};
<span class="hljs-built_in">console</span>.log(p);
</code></pre>
<p>We start with the same object. But instead of changing an object's property value directly, we again use the spread operator. The spread operator makes a copy of the object by spreading it into a new object at a new address. We update the property in that new object. We then reassign the <code>p</code> variable to the address of the new object.</p>
<p><img src="https://lh7-us.googleusercontent.com/_q_uW95z9GHcZi2SgUUpI1ht1P7dWqY4xF0z8P8cphnmMb_EkUwogdYQaGf1ZaqfKLxKtbWtzUDRZMtVcv8CiK3Zog5c1Wv6187x5gCeaTi8g_27x2HBRXucBbRHI9huMzh08VbE3CpM30mSlrLUiQc" alt="Image" width="1300" height="1352" loading="lazy">
<em>Figure 8. Using the spread operator, we create a new object at a new address and assign it to the <code>p</code> variable.</em></p>
<p>Notice that the original object is not changed. By using the spread operator, we achieve immutability.</p>
<p>So we've seen how primitives are immutable by default. And that arrays and objects are mutable, but we can work with them in an immutable way.</p>
<p>Nice! But why do we care?</p>
<h2 id="heading-why-is-immutability-important">Why Is Immutability Important?</h2>
<p>There are several reasons that immutability is important to our everyday coding.</p>
<ul>
<li>Once an immutable value is set, it isn't changed. Rather a new value is created. This makes the value predictable and consistent throughout the code. So it aids in managing state throughout the application. Plus immutability is a key principle in state management frameworks, such as Redux.</li>
<li>Code becomes simpler and less error-prone when data structures don't change unexpectedly. This also simplifies debugging and maintenance.</li>
<li>Embracing immutability is in line with functional programming principles, leading to fewer side effects and more predictable code.</li>
</ul>
<h2 id="heading-wrapping-up"><strong>Wrapping Up</strong></h2>
<p>Immutability is a fundamental concept in programming. An immutable value is a value that can not be changed after it has been created. </p>
<p>This concept is important to functional programming and state management. It's a valuable concept, especially when dealing with concurrency and large, complex codebases.</p>
<p>To see these concepts with animations, check out the video here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/DBZESPS-5mQ" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>Or try my stackblitz link: <a target="_blank" href="https://stackblitz.com/edit/immutability-deborahk">https://stackblitz.com/edit/immutability-deborahk</a>. Be sure to fork my project to try out your own changes.</p>
<p>While JavaScript objects and arrays are mutable by default, adopting an immutable approach to handling them can lead to cleaner, more reliable, and easier-to-maintain code.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Mutability vs Immutability in JavaScript – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Chukwunonso Nwankwo In JavaScript, different data types have different behaviors and locations in memory. So to reduce the chances of having bugs in your code, you need to understand the concept of mutability and immutability in JavaScript.  Mutab... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/mutability-vs-immutability-in-javascript/</link>
                <guid isPermaLink="false">66d45e0151f567b42d9f8452</guid>
                
                    <category>
                        <![CDATA[ immutability ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 05 May 2023 18:20:10 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/purple-balls-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Chukwunonso Nwankwo</p>
<p>In JavaScript, different data types have different behaviors and locations in memory. So to reduce the chances of having bugs in your code, you need to understand the concept of mutability and immutability in JavaScript. </p>
<p>Mutability refers to data types that can be accessed and changed after they've been created and stored in memory. Immutability, on the other hand, refers to data types that you can't change after creating them – but that you can still access in the memory.</p>
<p>This article will help you to fully grasp the concept of mutability and immutability of data in JavaScript. We'll begin with understanding the different data types and go from there. </p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>Knowledge of how variables work in JavaScript</li>
<li>Knowledge of how objects work in JavaScript</li>
</ul>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ul>
<li><a class="post-section-overview" href="#heading-what-are-primitve-data-types-in-javascript">What are Primitve Data Types in JavaScript?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-reference-data-types-in-javascript">What are Reference Data Types in JavaScript?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-clone-object-properties">How to Clone Object Properties</a></li>
<li><a class="post-section-overview" href="#heading-what-is-immutability-in-javascript">What is Immutability in JavaScript?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-prevent-object-mutability">How to Prevent Object Mutability</a></li>
<li><a class="post-section-overview" href="#heading-const-immutability">const != Immutability</a></li>
<li><a class="post-section-overview" href="#heading-final-thoughts">Final Thoughts</a></li>
</ul>
<h1 id="heading-data-types-in-javascript">Data Types in JavaScript</h1>
<p>Data types are categorized into <code>Primitive</code> and <code>Reference</code> types in JavaScript. Before explaining these categories, let's look at two important terms with regards to memory that you will need to know: the <code>Stack</code> and <code>Heap</code>.</p>
<h3 id="heading-what-is-the-stack">What is the Stack?</h3>
<p>Stack is a data structure that obeys the <code>Last In First Out</code> (LIFO) principle. This implies that the last item to enter the <code>stack</code> goes out first. </p>
<p>Imagine a pile of books stacked up on a shelf. The last book ends up being the first to be removed. Data stored inside the stack can still be accessed easily.</p>
<h3 id="heading-what-is-the-heap">What is the Heap?</h3>
<p>Reference data are stored inside the <code>heap</code>. When reference data is created, the variable of the data is placed on the <code>stack</code> but the actual value is placed on the <code>heap</code>. </p>
<h2 id="heading-what-are-primitve-data-types-in-javascript">What are Primitve Data Types in JavaScript?</h2>
<p>Primitive data types are immutable and are not objects because they lack properties and methods.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/data-types-1.png" alt="data-types-1" width="600" height="400" loading="lazy"></p>
<p>To determine the kind of data you are working with, use the <code>typeof</code> operator. The <code>typeof</code> operator works perfectly with all primitive data types except <code>null</code>. </p>
<h3 id="heading-primitive-data-type-examples">Primitive Data Type Examples</h3>
<p>Let's look at some examples of primitive data types now to get a better understanding of what they are and how they work</p>
<p>Here's an example of a number:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> num = <span class="hljs-number">23</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> num)
</code></pre>
<p>Here's an example of a string:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"Table"</span>
</code></pre>
<p>Here's an example of an undefined variable. A variable is said to be undefined if there are no values attached to it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> figure;

 <span class="hljs-string">`null`</span>

   <span class="hljs-keyword">let</span> fig = <span class="hljs-literal">null</span>

   <span class="hljs-built_in">console</span>.log(fig)

   <span class="hljs-built_in">console</span>.log(fig === <span class="hljs-literal">null</span>)
</code></pre>
<p>Keep in mind that <code>null</code> is not same as <code>Null</code> or <code>NULL</code>.</p>
<p>Here's an example of a boolean. This primitive data type is either <code>true</code> or <code>false</code>.</p>
<pre><code class="lang-js">   <span class="hljs-keyword">let</span> student = <span class="hljs-literal">true</span>;

   <span class="hljs-keyword">let</span> married = <span class="hljs-literal">false</span>;
</code></pre>
<p>Booleans are not strings – notice that <code>true</code> or <code>false</code> are not in quotes.</p>
<p>Here's an example of a symbol. As a primitive data type, symbols are unique. The values that are returned are also guaranteed to be unique.</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> mySymbol = <span class="hljs-built_in">Symbol</span>();

   <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> mySymbol) <span class="hljs-comment">//Symbol</span>
</code></pre>
<p>Here's an example of BigInit. Use <code>BigInt</code> when the values you are working on are too big for the number data types.</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> myBigInt = <span class="hljs-number">12n</span>;

   <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> myBigInt) <span class="hljs-comment">//BigInt</span>

   <span class="hljs-keyword">const</span> check = BigInt(<span class="hljs-number">414242532</span>)

   <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> check)
</code></pre>
<h2 id="heading-what-are-reference-data-types-in-javascript">What are Reference Data Types in JavaScript?</h2>
<p>By default, reference data types are mutable. Reference data types consist of <code>Functions</code>, <code>Arrays</code>, and <code>Objects</code>.  </p>
<p>Let's look at some examples of reference data types to help you understand better:</p>
<p>Here's an example of a function:</p>
<pre><code class="lang-js">   <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">favorite</span>(<span class="hljs-params">question</span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi dear, do you like <span class="hljs-subst">${question}</span> programming language?`</span>)
   }

   favorite(<span class="hljs-string">'JavaScript'</span>)
</code></pre>
<p>Here's an example of an array:</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> countriesVisited = [<span class="hljs-string">'Nigeria'</span>, <span class="hljs-string">'Japan'</span>, <span class="hljs-string">'Australia'</span>]

   <span class="hljs-built_in">console</span>.log(countriesVisited)
</code></pre>
<p>Here's an example of an object:</p>
<pre><code class="lang-js">
   <span class="hljs-keyword">const</span> touristData = {
      <span class="hljs-attr">firstname</span>: <span class="hljs-string">'Camila'</span>,
      <span class="hljs-attr">lastname</span>: <span class="hljs-string">'Pedro'</span>,
      <span class="hljs-attr">Nationality</span>: <span class="hljs-string">'Spanish'</span>
   }
   <span class="hljs-built_in">console</span>.log(touristData)
</code></pre>
<p>Just for clarity, the firstname is called the <code>key</code> while Camila is the <code>value</code>.</p>
<p>Reference data types place the variable on the <code>stack</code>. The variable serves as a pointer that points to the <code>object</code> located on the <code>heap.</code> </p>
<p>The main distinction between these categories is that Primitives are <code>immutable</code> but References are <code>mutable</code>. Now, let's get to the meat of the matter.</p>
<h1 id="heading-what-is-mutability-in-javascript">What is Mutability in JavaScript?</h1>
<p>If a data type is mutable, that means that you can change it. Mutability allows you to modify existing values without creating new ones. </p>
<p>For every <code>object</code>, a pointer is added to the <code>stack</code>, and this pointer points to the <code>object</code> on the <code>heap</code>.  </p>
<p>Take, for example, the following code: </p>
<pre><code class="lang-js">    <span class="hljs-keyword">const</span> staff = {
         <span class="hljs-attr">name</span>: <span class="hljs-string">"Strengthened"</span>,
         <span class="hljs-attr">age</span>: <span class="hljs-number">43</span>,
         <span class="hljs-attr">Hobbies</span>: [<span class="hljs-string">"reading"</span>, <span class="hljs-string">"Swimming"</span>]
   }
</code></pre>
<p>On the stack you will find <code>staff</code> which is a pointer to the actual object on the <code>heap</code>.</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> staff2 = staff;

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

   <span class="hljs-built_in">console</span>.log(staff2);
</code></pre>
<p>Another pointer is placed on the <code>stack</code> when <code>staff</code> was assigned to <code>staff2</code>. Now, these pointers point to a single object on the <code>heap</code>.</p>
<p>Reference data does not copy values, but rather pointers.</p>
<pre><code class="lang-js">   staff2.age = <span class="hljs-number">53</span>;

   <span class="hljs-built_in">console</span>.log(staff)

   <span class="hljs-built_in">console</span>.log(staff2)
</code></pre>
<p>Changing the <code>age</code> of <code>staff2</code> updates the <code>age</code> of the <code>staff</code> object. Now you know it is because both point to the same object. </p>
<p>  <img src="https://www.freecodecamp.org/news/content/images/2023/04/reference2-1.png" alt="reference2-1" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-clone-object-properties">How to Clone Object Properties</h2>
<p>You can clone the properties of an object using the <code>Object. assign()</code> method and the <code>spread</code> operator. With these, you can change the properties of the cloned object without changing the properties of the object from which it was cloned.</p>
<h3 id="heading-how-the-objectassign-method-works">How the <code>Object.assign()</code> method Works</h3>
<p>The <code>object.assign</code> method copies properties from an object (the source) into another object (the target) and returns the modified target object.</p>
<p>Here's the syntax:</p>
<p><code>Object.assign(target, source)</code></p>
<p>The method has two arguments, <code>target</code> and <code>source.</code> The <code>target</code> is the object that receives new properties, while the <code>source</code> is where the properties come from. The <code>target</code> can be an empty object <code>{}.</code> </p>
<p>In a situation where the <code>source</code> and <code>target</code> share the same <code>key</code>, the <code>source</code> object overwrites the value of the <code>key</code> on the target.</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> staff = {
      <span class="hljs-attr">name</span>: <span class="hljs-string">"Strengthened"</span>,
      <span class="hljs-attr">age</span>: <span class="hljs-number">43</span>,
      <span class="hljs-attr">Hobbies</span>: [<span class="hljs-string">"reading"</span>, <span class="hljs-string">"Swimming"</span>]
   }

   <span class="hljs-keyword">const</span> staff2 = <span class="hljs-built_in">Object</span>.assign({}, staff);
</code></pre>
<p>The properties on the <code>staff</code> object were cloned into an empty <code>target</code>. </p>
<p><code>staff2</code> now has its own properties. You can prove this by changing the value of any of its properties. Making this change will not affect the values of the properties on the <code>staff</code> object.</p>
<pre><code class="lang-js">   staff2.age = <span class="hljs-number">53</span>;

   <span class="hljs-built_in">console</span>.log(staff)

   <span class="hljs-built_in">console</span>.log(staff2)
</code></pre>
<p>The value of <code>staff2.age</code> that was changed to <code>53</code> does not in any way affect the value of <code>staff.age</code> because they both have their own properties.</p>
<h3 id="heading-how-the-spread-operator-works">How the <code>Spread</code> Operator Works</h3>
<p>Here's the syntax of the spread operator:</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> newObj = {...obj}
</code></pre>
<p>Using the <code>spread</code> operator is quite simple. You need to place three dots <code>...</code> before the name of the object whose properties you intend to clone:</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> staff = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Strengthened"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">43</span>,
    <span class="hljs-attr">Hobbies</span>: [<span class="hljs-string">"reading"</span>, <span class="hljs-string">"Swimming"</span>]
   }

   <span class="hljs-keyword">const</span> staff2 = {...staff};


   staff2.age = <span class="hljs-number">53</span>;

   <span class="hljs-built_in">console</span>.log(staff)

   <span class="hljs-built_in">console</span>.log(staff2)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/cloning.png" alt="cloning" width="600" height="400" loading="lazy"></p>
<h2 id="heading-what-is-immutability-in-javascript">What is Immutability in JavaScript?</h2>
<p>Immutability is the state where values are immutable (that is, not able to be changed). A value is immutable when altering it is impossible. Primitive data types are immutable, as we discussed above.</p>
<p>Let's look at an example:</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> num = <span class="hljs-number">46</span>;
   <span class="hljs-keyword">const</span> newNum = num;
</code></pre>
<p>Looking at the code above, <code>num</code> was reassigned to <code>newNum.</code> Now both <code>num</code> and <code>newNum</code> have a value of <code>46</code>. Changing the value on <code>newNum</code> will not alter the value on `num.</p>
<pre><code class="lang-js">      <span class="hljs-keyword">let</span> student1 = <span class="hljs-string">"Halina"</span>;

      <span class="hljs-keyword">let</span> student2 = student1;
</code></pre>
<p>In the code above, a variable called <code>student1</code> was created and assigned to <code>student2</code>.</p>
<pre><code class="lang-js">      student1 = <span class="hljs-string">"Brookes"</span>

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

      <span class="hljs-built_in">console</span>.log(student2)
</code></pre>
<p>Changing <code>student1</code> to <code>Brookes</code> does not change the initial value on <code>student2</code>. This proves that in primitive data types, actual values are copied, so both have their own. On the stack memory, <code>student1</code> and <code>student2</code> are distinct. </p>
<p>The stack obeys the <code>Last-In-First-Out</code> principle. The first item that enters the stack is the last item to go out and vice versa. Accessing items  stored in the stack is easy.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/primitive-1.png" alt="primitive-1" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-prevent-object-mutability">How to Prevent Object Mutability</h2>
<p>So far you have learned that objects are mutable by default.</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> studentNames = {
           <span class="hljs-attr">student1</span>: <span class="hljs-string">'Halina'</span>,
           <span class="hljs-attr">student2</span>: <span class="hljs-string">"Brookes"</span>,
           <span class="hljs-attr">student3</span>:<span class="hljs-string">"Anthony"</span>
   }


   <span class="hljs-built_in">Object</span>.defineProperty(studentNames, <span class="hljs-string">"student4"</span>, {
      <span class="hljs-attr">value</span>: <span class="hljs-string">"Mirabel"</span>,
   })

   <span class="hljs-built_in">console</span>.log(studentNames);
</code></pre>
<p>Now we've added <code>student4</code>.</p>
<p>To prevent object <code>mutability</code>, you can use the <code>Object.preventExtensions()</code>, <code>Object.seal()</code>, and <code>Object.freeze()</code> methods.</p>
<p>For all three methods, we will explore adding properties using dot notation and the <code>define</code> property, modifying properties using defineProperty, and deleting properties. </p>
<p>This will give you a better understanding of the capabilities and limitations of each method, and ultimately help you in determining which method may be best suited for a particular use case. </p>
<p>So, let's dive in and explore these methods in more detail.</p>
<h3 id="heading-how-to-use-the-objectpreventextensions-method">How to Use the <code>Object.preventExtensions</code> Method</h3>
<p>Here's the syntax of this method:</p>
<p><code>Object.preventExtensions(obj)</code></p>
<p>Using <code>Object.preventExtensions</code> stops new properties from entering the object. The object does not increase in size and maintains its properties. By default, all objects in JavaScript are extensible. With this method, you can delete properties from your object.</p>
<h4 id="heading-how-to-add-new-properties">How to add new properties</h4>
<ul>
<li>using <code>dot notation</code>:</li>
</ul>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> makeNonExtensive = {
           <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Charles"</span>,
           <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Chandlier"</span>
   }

   <span class="hljs-built_in">Object</span>.preventExtensions(makeNonExtensive)

   makeNonExtensive.designation = <span class="hljs-string">"Software Engineer"</span>;

   <span class="hljs-built_in">console</span>.log(makeNonExtensive)
</code></pre>
<p>Check the console – the <code>designation</code> property was not added and there's no error message.</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> obj = {
           <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Derek"</span>,
           <span class="hljs-attr">designation</span>: <span class="hljs-string">"Software Engineer"</span>
   }
</code></pre>
<ul>
<li>using the <code>defineProperty</code> method</li>
</ul>
<p>Here's the syntax:</p>
<pre><code class="lang-js">   <span class="hljs-built_in">Object</span>.defineProperty(obj, prop, descriptor)
</code></pre>
<p>Here's what's going on in that code:</p>
<ul>
<li><code>obj</code>: The object you want to add properties to.</li>
<li><code>prop</code>: You define the name of the property you want to add or change. It should be either a string or symbol</li>
<li><code>Descriptor</code>: You include the value of the property.</li>
</ul>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> makeNonExtensive = {
           <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Charles"</span>,
           <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Chandlier"</span>
   }

   <span class="hljs-built_in">Object</span>.preventExtensions(makeNonExtensive)

   <span class="hljs-built_in">Object</span>.defineProperty(makeNonExtensive, <span class="hljs-string">"age"</span>, {
      <span class="hljs-attr">value</span>: <span class="hljs-string">"twenty"</span>,
   })

   <span class="hljs-built_in">console</span>.log(makeNonExtensive)
</code></pre>
<ul>
<li>Adding new properties using the define property throws this error message: <code>index.js:361 Uncaught TypeError: Cannot define property age, object is not extensible</code>.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/define-prop-cons.png" alt="define-prop-cons" width="600" height="400" loading="lazy"></p>
<h4 id="heading-how-to-modify-an-existing-property-using-the-define-property">How to modify an existing property using the <code>define Property</code></h4>
<pre><code class="lang-js">    <span class="hljs-keyword">const</span> makeNonExtensive = {
            <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Charles"</span>,
            <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Chandlier"</span>
    }

   <span class="hljs-built_in">Object</span>.preventExtensions(makeNonExtensive)

   <span class="hljs-built_in">Object</span>.defineProperty(makeNonExtensive, <span class="hljs-string">'firstname'</span>, {
    <span class="hljs-attr">value</span>: <span class="hljs-string">'Jason'</span>,
    })
    <span class="hljs-built_in">console</span>.log(makeNonExtensive)
</code></pre>
<p>The value of the property of a non-extensible object can be changed as demonstrated with the above line of code.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/modify-pext-1.png" alt="modify-pext-1" width="600" height="400" loading="lazy"></p>
<h4 id="heading-how-to-delete-a-property">How to delete a property</h4>
<p>Here's the syntax:</p>
<pre><code>   <span class="hljs-keyword">delete</span> object.propertyname
</code></pre><pre><code class="lang-js">   <span class="hljs-keyword">const</span> makeNonExtensive = {
           <span class="hljs-attr">firstname</span>: <span class="hljs-string">"Charles"</span>,
           <span class="hljs-attr">lastname</span>: <span class="hljs-string">"Chandlier"</span>
   }

   <span class="hljs-built_in">Object</span>.preventExtensions(makeNonExtensive)

   <span class="hljs-keyword">delete</span> makeNonExtensive.lastname

   <span class="hljs-built_in">console</span>.log(makeNonExtensive)
</code></pre>
<p>In spite of the object being non-extensible, the <code>lastname</code> property was deleted.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/pExtension-del-1.png" alt="pExtension-del-1" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-use-objectseal">How to Use <code>Object.seal()</code></h3>
<p>All objects in Javascript are extensible by default. Just as the name suggests, this method seals an object. You cannot add new properties to a sealed object or delete an existing property from a sealed object. But <code>object.seal</code> permits modifying existing properties.</p>
<p>Here's the syntax:</p>
<pre><code><span class="hljs-built_in">Object</span>.seal()
</code></pre><h4 id="heading-how-to-add-new-properties-1">How to add new properties</h4>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> studentNames = {
           <span class="hljs-attr">student1</span>: <span class="hljs-string">'Halina'</span>,
           <span class="hljs-attr">student2</span>: <span class="hljs-string">"Brookes"</span>, 
           <span class="hljs-attr">student3</span>:<span class="hljs-string">"Alina"</span>
   }

   <span class="hljs-built_in">Object</span>.seal(studentNames)

   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.isSealed(studentNames))
</code></pre>
<p><code>Object.isSealed(studentNames)</code> is used to check if an object is sealed.</p>
<h4 id="heading-how-to-use-dot-notation">How to use <code>dot notation</code></h4>
<pre><code class="lang-js">   studentNames.student4 = <span class="hljs-string">"Barbara"</span>;

   <span class="hljs-built_in">console</span>.log(studentNames)
</code></pre>
<p>Without producing an error, the dot notation fails when adding the new property <code>student4</code>. </p>
<h4 id="heading-how-to-use-the-defineproperty-method">How to use the <code>defineProperty</code> method</h4>
<pre><code class="lang-js">      <span class="hljs-keyword">const</span> studentNames = {
              <span class="hljs-attr">student1</span>: <span class="hljs-string">'Halina'</span>,
              <span class="hljs-attr">student2</span>: <span class="hljs-string">"Brookes"</span>,
              <span class="hljs-attr">student3</span>:<span class="hljs-string">"Alina"</span>
      }

      <span class="hljs-built_in">Object</span>.seal(studentNames)

      <span class="hljs-built_in">Object</span>.defineProperty(studentNames, <span class="hljs-string">'student4'</span>, {
         <span class="hljs-attr">value</span>: <span class="hljs-string">'Barbara'</span>
      })

      <span class="hljs-built_in">console</span>.log(studentNames)
</code></pre>
<p>The error message "Uncaught TypeError: Cannot define property student4, the object is not extendable" is thrown when attempting to add the same property using the <code>define property</code> method.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/seal1-2.png" alt="seal1-2" width="600" height="400" loading="lazy"></p>
<h4 id="heading-how-to-modify-an-existing-property-using-define-property">How to modify an existing property using <code>define Property</code></h4>
<pre><code class="lang-js">
      <span class="hljs-keyword">const</span> studentNames = {
              <span class="hljs-attr">student1</span>: <span class="hljs-string">'Halina'</span>,
              <span class="hljs-attr">student2</span>: <span class="hljs-string">"Brookes"</span>,
              <span class="hljs-attr">student3</span>:<span class="hljs-string">"Alina"</span>
      }

         <span class="hljs-built_in">Object</span>.seal(studentNames)

      <span class="hljs-built_in">Object</span>.defineProperty(studentNames, <span class="hljs-string">'student2'</span>, {
         <span class="hljs-attr">value</span>: <span class="hljs-string">"Water-Brookes"</span>,
      })

      <span class="hljs-built_in">console</span>.log(studentNames)
</code></pre>
<p>Now <code>student2</code> has been changed from "Brookes" to "Water-Brookes".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/seal2.png" alt="seal2" width="600" height="400" loading="lazy"></p>
<h4 id="heading-how-to-delete-a-property-1">How to delete a property</h4>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> studentNames = {
           <span class="hljs-attr">student1</span>: <span class="hljs-string">'Halina'</span>,
           <span class="hljs-attr">student2</span>: <span class="hljs-string">"Brookes"</span>,
           <span class="hljs-attr">Student3</span>:<span class="hljs-string">"Alina"</span>
   }

   <span class="hljs-built_in">Object</span>.seal(studentNames)

   <span class="hljs-keyword">delete</span> studentNames.student1

   <span class="hljs-built_in">console</span>.log(studentNames)
</code></pre>
<p>Properties cannot be removed from sealed objects. In the console, student1 still remains.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/seal3-2.png" alt="seal3-2" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-use-objectfreeze">How to Use <code>Object.freeze()</code></h3>
<p>Here's the syntax:</p>
<pre><code>   <span class="hljs-built_in">Object</span>.freeze()
</code></pre><p>The <code>Object.freeze()</code> method freezes an object. Using this method guarantees high integrity by ensuring that pulling out, modifying existing properties, or adding new properties to the object will not be possible. </p>
<p>To check if an object is frozen, use the syntax below:</p>
<pre><code>   <span class="hljs-built_in">Object</span>.isFrozen(obj);
</code></pre><p>Even when you apply the <code>object.freeze</code> to an object, you can add new property, modify an existing property, or delete properties from objects nested under it. </p>
<p>Just as we have done for other methods, let's explore the object.freeze method in relation to adding new properties, modifying values, or deleting properties from an object.</p>
<h4 id="heading-how-to-add-new-properties-2">How to add new properties</h4>
<ul>
<li>Using <code>dot notation</code></li>
</ul>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> teamplayers = {
           <span class="hljs-attr">player1</span>: <span class="hljs-string">"Andrey"</span>,
           <span class="hljs-attr">player2</span>: <span class="hljs-string">"Abundance"</span>
   }


   <span class="hljs-built_in">Object</span>.freeze(teamplayers)

   teamplayers.player3 = <span class="hljs-string">"Finder"</span>;

   <span class="hljs-built_in">console</span>.log(teamplayers)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/freeze-dot.png" alt="freeze-dot" width="600" height="400" loading="lazy"></p>
<p>Notice that <code>player3</code> was not added.</p>
<ul>
<li>Using the <code>defineProperty</code> method</li>
</ul>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> teamplayers = {
           <span class="hljs-attr">player1</span>: <span class="hljs-string">"Andrey"</span>,
           <span class="hljs-attr">player2</span>: <span class="hljs-string">"Abundance"</span>
   }


   <span class="hljs-built_in">Object</span>.freeze(teamplayers)

   <span class="hljs-built_in">Object</span>.defineProperty(teamplayers, <span class="hljs-string">'player3'</span>, {
      <span class="hljs-attr">value</span>: <span class="hljs-string">'Charis'</span>
      })
      <span class="hljs-built_in">console</span>.log(teamplayers)

   <span class="hljs-built_in">console</span>.log(teamplayers)
</code></pre>
<p>Dot notation fails silently when trying to add a property, but <code>defineproperty</code> throws a TypeError instead.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/freeze1.png" alt="freeze1" width="600" height="400" loading="lazy"></p>
<h4 id="heading-how-to-modify-an-existing-property">How to modify an existing property</h4>
<pre><code class="lang-js">
   <span class="hljs-keyword">const</span> teamplayers = {
           <span class="hljs-attr">player1</span>: <span class="hljs-string">"Andrey"</span>,
           <span class="hljs-attr">player2</span>: <span class="hljs-string">"Abundance"</span>
   }


   <span class="hljs-built_in">Object</span>.freeze(teamplayers)


   teamplayers.player1 = <span class="hljs-string">"Christabel"</span>

   <span class="hljs-built_in">console</span>.log(teamplayers)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/freeze2.png" alt="freeze2" width="600" height="400" loading="lazy"></p>
<p>This will fail silently. But with the define property below a <code>typeError</code> is thrown.</p>
<pre><code class="lang-js">
      <span class="hljs-keyword">const</span> teamplayers = {
              <span class="hljs-attr">player1</span>: <span class="hljs-string">"Andrey"</span>,
              <span class="hljs-attr">player2</span>: <span class="hljs-string">"Abundance"</span>
      }


      <span class="hljs-built_in">Object</span>.freeze(teamplayers)


      <span class="hljs-built_in">Object</span>.defineProperty(teamplayers, <span class="hljs-string">'player1'</span>, {
         <span class="hljs-attr">value</span>: <span class="hljs-string">"Anne"</span>
      })

      <span class="hljs-built_in">console</span>.log(teamplayers)
</code></pre>
<p> <code>Uncaught TypeError: Cannot redefine property: player1</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/freeze3.png" alt="freeze3" width="600" height="400" loading="lazy"></p>
<h4 id="heading-how-to-delete-a-property-2">How to delete a property</h4>
<pre><code class="lang-js">
   <span class="hljs-keyword">const</span> teamplayers = {
           <span class="hljs-attr">player1</span>: <span class="hljs-string">"Andrey"</span>,
           <span class="hljs-attr">player2</span>: <span class="hljs-string">"Abundance"</span>
   }


   <span class="hljs-built_in">Object</span>.freeze(teamplayers)


   <span class="hljs-keyword">delete</span> teamplayers.player2

   <span class="hljs-built_in">console</span>.log(teamplayers)
</code></pre>
<p>Attempting to delete a property on a frozen object also fails silently.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/freeze4.png" alt="freeze4" width="600" height="400" loading="lazy"></p>
<h4 id="heading-how-to-use-deep-freeze">How to use Deep Freeze</h4>
<pre><code class="lang-js">
   <span class="hljs-keyword">const</span> teamplayers = {
           <span class="hljs-attr">player1</span>: <span class="hljs-string">"Andrey"</span>,
           <span class="hljs-attr">player2</span>: <span class="hljs-string">"Abundance"</span>,
                   <span class="hljs-attr">substitutes</span>: {
                   <span class="hljs-attr">player3</span>: <span class="hljs-string">"Jeremiah"</span>,
                   <span class="hljs-attr">player4</span>: <span class="hljs-string">"Jayden"</span>
            }
   }

   <span class="hljs-keyword">const</span> squad = teamplayers;

   <span class="hljs-built_in">Object</span>.freeze(teamplayers)


   <span class="hljs-built_in">Object</span>.defineProperty(teamplayers.substitutes, <span class="hljs-string">'player5'</span>, {
      <span class="hljs-attr">value</span>: <span class="hljs-string">"Woodland"</span>
   })

   <span class="hljs-built_in">console</span>.log(teamplayers)
</code></pre>
<p>Player5 has been added to the nested <code>substitutes</code> even though the <code>object.freeze</code> method was applied to the parent <code>teamplayers</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/deep1.png" alt="deep1" width="600" height="400" loading="lazy"></p>
<p>You can also modify the value of the properties in the nested object.</p>
<ul>
<li>How to delete a property</li>
</ul>
<pre><code class="lang-js">   <span class="hljs-keyword">delete</span> teamplayers.substitutes.player3

   <span class="hljs-built_in">console</span>.log(teamplayers)
</code></pre>
<p>Player3 has been removed. Everything that the object.freeze prevents on the parent object is obtainable on the child object that is nested.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/deep2.png" alt="deep2" width="600" height="400" loading="lazy"></p>
<p>To prevent this, we employ the deep freeze technique as shown below:</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> deepVal = <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>) deepVal(obj[prop]);
        });
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">Object</span>.freeze(obj);
    };

    <span class="hljs-keyword">const</span> teamplayers = deepVal( {
            <span class="hljs-attr">player1</span>: <span class="hljs-string">"Andrey"</span>,
            <span class="hljs-attr">player2</span>: <span class="hljs-string">"Abundance"</span>,
                    <span class="hljs-attr">substitutes</span>: {
                        <span class="hljs-attr">player3</span>: <span class="hljs-string">"Jeremiah"</span>,
                        <span class="hljs-attr">player4</span>: <span class="hljs-string">"Jayden"</span>
                    }
            }
    )
   <span class="hljs-keyword">const</span> squad = teamplayers;

   <span class="hljs-built_in">Object</span>.freeze(teamplayers)

   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.isFrozen(teamplayers));

   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.isFrozen(squad));
</code></pre>
<ul>
<li>How to add a new property to the child object.</li>
</ul>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> deepVal = <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>) deepVal(obj[prop]);
        });
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">Object</span>.freeze(obj);
 };

    <span class="hljs-keyword">const</span> teamplayers = deepVal( {
            <span class="hljs-attr">player1</span>: <span class="hljs-string">"Andrey"</span>,
            <span class="hljs-attr">player2</span>: <span class="hljs-string">"Abundance"</span>,
                    <span class="hljs-attr">substitutes</span>: {
                        <span class="hljs-attr">player3</span>: <span class="hljs-string">"Jeremiah"</span>,
                        <span class="hljs-attr">player4</span>: <span class="hljs-string">"Jayden"</span>
                    }
            }
    )

   <span class="hljs-built_in">Object</span>.freeze(teamplayers)

   <span class="hljs-built_in">Object</span>.defineProperty(teamplayers.substitutes, <span class="hljs-string">'player5'</span>, {
      <span class="hljs-attr">value</span>: <span class="hljs-string">"Alice"</span>
   })

   <span class="hljs-built_in">console</span>.log(teamplayers)
</code></pre>
<p>Now when you attempt adding a property, you will get this error <code>Uncaught TypeError: Cannot define property player5, object is not extensible</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/deep-addd-1.png" alt="deep-addd-1" width="600" height="400" loading="lazy"></p>
<p>Also deep freeze prevents you from changing and deleting properties of an object.</p>
<h2 id="heading-const-immutability">const != Immutability</h2>
<p>A variable declared using the <code>let</code> keyword can be reassigned using the assignment operator (<code>=</code>). Take a look at the code below to understand what I mean.</p>
<pre><code class="lang-js">   <span class="hljs-keyword">let</span> num = <span class="hljs-number">34</span>;
   num = <span class="hljs-number">50</span>;

   <span class="hljs-built_in">console</span>.log(num);
</code></pre>
<p>Here, after declaring variable <code>num</code> using the <code>let</code> keyword, the value was reassigned from 34 to 50.</p>
<p>However, you cannot achieve the same thing on the same variable declared using the <code>const</code> keyword. </p>
<pre><code class="lang-js"> <span class="hljs-keyword">const</span> num = <span class="hljs-number">34</span>;
 num = <span class="hljs-number">50</span>;

 <span class="hljs-built_in">console</span>.log(num);
</code></pre>
<p>You will get this error <code>Uncaught TypeError: Assignment to constant variable</code>.</p>
<p>But that is not the case with objects. An object that you declared using <code>const</code> is still mutable, so you can still modify the properties of that particular object as you can see below:</p>
<pre><code class="lang-js">   <span class="hljs-keyword">const</span> getObj = {
           <span class="hljs-attr">color1</span>: <span class="hljs-string">"Green"</span>,
           <span class="hljs-attr">color2</span>: <span class="hljs-string">"Blue"</span>,
           <span class="hljs-attr">color3</span>: <span class="hljs-string">"Yellow"</span>
   }

   getObj.color1 = <span class="hljs-string">"Brown"</span>;

   <span class="hljs-built_in">console</span>.log(getObj.color1)
</code></pre>
<p>The value of <code>color1</code> was altered from <code>Green</code> to <code>Brown</code>, even when declared with <code>const</code>.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>You've now learned about the various data types and whether they are immutable or mutable by default. </p>
<p>Objects can be changed by default. But using specific methods like the Object.seal, Object.freeze, and preventExtensions can prevent mutability. </p>
<p>The level of immutability provided by these methods varies, so make sure you use the one that corresponds to the integrity level you want to accomplish. Until next time, keep exploring JavaScript.</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[ 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[ 30 Seconds of Code: How to rename multiple object keys in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ By Yazeed Bzadough 30 Seconds of Code is a brilliant collection of JavaScript snippets, digestible in ≤ 30 seconds. Anyone looking to master JavaScript should go through the entire thing. The list didn’t contain a function to rename multiple object k... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/30-seconds-of-code-rename-many-object-keys-in-javascript-268f279c7bfa/</link>
                <guid isPermaLink="false">66d4617bd7a4e35e384349c7</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ immutability ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 13 Apr 2018 11:55:29 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*qlRItHMmEVJGSEDRYJbGLA.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Yazeed Bzadough</p>
<p>30 Seconds of Code is a brilliant collection of JavaScript snippets, digestible in ≤ 30 seconds. <strong>Anyone looking to master JavaScript should go through the entire thing.</strong></p>
<p>The list didn’t contain a function to rename multiple object keys, however, so I created a <a target="_blank" href="https://github.com/Chalarangelo/30-seconds-of-code/pull/646">pull request</a> that thankfully got merged!</p>
<p>Here’s the official entry: <a target="_blank" href="https://30secondsofcode.org/object#renamekeys">https://30secondsofcode.org/object#renamekeys</a></p>
<p>I’ve previously written on <a target="_blank" href="https://medium.com/front-end-hacking/immutably-rename-object-keys-in-javascript-5f6353c7b6dd">renaming object keys</a>, but we only changed one key at a time.</p>
<p>Then <a target="_blank" href="https://medium.com/@adaminsley">Adam Rowe</a> kindly commented, asking how we might rename <em>multiple</em> object keys. I replied with this code sample after some thought and research.</p>
<pre><code class="lang-js">renameKeys = <span class="hljs-function">(<span class="hljs-params">keysMap, obj</span>) =&gt;</span>
  <span class="hljs-built_in">Object</span>.keys(obj).reduce(
    <span class="hljs-function">(<span class="hljs-params">acc, key</span>) =&gt;</span> ({
      ...acc,
      ...{ [keysMap[key] || key]: obj[key] }
    }),
    {}
  );
</code></pre>
<p>This was inspired by <a target="_blank" href="https://char0n.github.io/ramda-adjunct/2.6.0/RA.html#.renameKeys">Ramda Adjunct</a>’s <code>renameKeys</code> function.</p>
<ul>
<li><code>keysMap</code> contains key/value pairs of your old/new object keys.</li>
<li><code>obj</code> is the object to be changed.</li>
</ul>
<p>You might use it like this:</p>
<pre><code class="lang-js">keysMap = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'firstName'</span>,
  <span class="hljs-attr">job</span>: <span class="hljs-string">'passion'</span>
};

obj = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Bobo'</span>,
  <span class="hljs-attr">job</span>: <span class="hljs-string">'Front-End Master'</span>
};

renameKeys(keysMap, obj);
<span class="hljs-comment">// { firstName: 'Bobo', passion: 'Front-End Master' }</span>
</code></pre>
<p>Let’s step through it! We can write an expanded, <code>debugger</code>-friendly version of this function:</p>
<pre><code class="lang-js">renameKeys = <span class="hljs-function">(<span class="hljs-params">keysMap, obj</span>) =&gt;</span> {
  <span class="hljs-keyword">debugger</span>;

  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Object</span>.keys(obj).reduce(<span class="hljs-function">(<span class="hljs-params">acc, key</span>) =&gt;</span> {
    <span class="hljs-keyword">debugger</span>;

    <span class="hljs-keyword">const</span> renamedObject = {
      [keysMap[key] || key]: obj[key]
    };

    <span class="hljs-keyword">debugger</span>;

    <span class="hljs-keyword">return</span> {
      ...acc,
      ...renamedObject
    };
  }, {});
};
</code></pre>
<p>And we’ll use it like this:</p>
<pre><code class="lang-js">renameKeys(
  {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'firstName'</span>,
    <span class="hljs-attr">job</span>: <span class="hljs-string">'passion'</span>
  },
  {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Bobo'</span>,
    <span class="hljs-attr">job</span>: <span class="hljs-string">'Front-End Master'</span>
  }
);
</code></pre>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*C9BI6jfACst-UcchX6wyyA.png" alt="1*C9BI6jfACst-UcchX6wyyA" width="1600" height="598" loading="lazy"></p>
<p>Pausing on line 2, we see that <code>keysMap</code> and <code>obj</code> have been properly assigned.</p>
<p>Here’s where the fun begins. Move to the next <code>debugger</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*3HKJjlIj8tChHNlre9WV9Q.png" alt="1*3HKJjlIj8tChHNlre9WV9Q" width="1600" height="687" loading="lazy"></p>
<p>Inspect our local variables on line 7:</p>
<ul>
<li><code>acc: {}</code> because that’s <code>Array.reduce()</code>’s initial value (line 19).</li>
<li><code>key: “name”</code> because it’s the first key from <code>Object.keys(obj)</code>.</li>
<li><code>renamedObject: undefined</code></li>
</ul>
<p>Also notice that we can access <code>keysMap</code> and <code>obj</code> from the parent function’s scope.</p>
<p>Guess what <code>renamedObject</code> will be. Like in my <a target="_blank" href="https://medium.com/front-end-hacking/immutably-rename-object-keys-in-javascript-5f6353c7b6dd">aforementioned post</a>, we’re using <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer"><em>computed property names</em></a> to dynamically assign <code>renamedObject</code>'s key.</p>
<p>If <code>keysMap[key]</code> exists, use it. Otherwise, use the original object key. In this case, <code>keysMap[key]</code> is <code>“firstName”</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*aYI7ss4IOWIipNsC40r9rg.png" alt="1*aYI7ss4IOWIipNsC40r9rg" width="1104" height="416" loading="lazy"></p>
<p>That’s <code>renamedObject</code>'s key, what about its corresponding value?</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*GEBIVtNMWIuosMVq4FLMQw.png" alt="1*GEBIVtNMWIuosMVq4FLMQw" width="980" height="266" loading="lazy"></p>
<p>It’s <code>obj[key]</code>: <code>"Bobo"</code>. Hit the next <code>debugger</code> and check it out.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*XMGM2FxuNscmq_imZf8Nmw.png" alt="1*XMGM2FxuNscmq_imZf8Nmw" width="1600" height="608" loading="lazy"></p>
<p><code>renamedObject</code> is now <code>{ firstName: “Bobo” }</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*z8HEVhgr8-e5HFrtAK5lzg.png" alt="1*z8HEVhgr8-e5HFrtAK5lzg" width="870" height="426" loading="lazy"></p>
<p>Now using the <em>spread</em> operator, we’ll merge <code>acc</code> and <code>renamedObject</code>. Remember that <code>acc</code> is currently <code>.reduce</code>'s initial value: an empty object.</p>
<p>So merging <code>acc</code> and <code>renamedObject</code> just results in a clone of <code>renamedObject</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*Fw0QyV7VsU2UH-GtD-74WQ.png" alt="1*Fw0QyV7VsU2UH-GtD-74WQ" width="1298" height="992" loading="lazy"></p>
<p>Since we’re returning this object, however, it becomes <code>acc</code> in <code>.reduce</code>’s next iteration. Move to the next <code>debugger</code> to see this.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*h0Lxhtw1trErPruUBKamfA.png" alt="1*h0Lxhtw1trErPruUBKamfA" width="1600" height="651" loading="lazy"></p>
<p>We’re inside <code>.reduce</code>'s again, because there’s one more <code>key</code> to process. We see that <code>acc</code> is now <code>{ firstName: "Bobo" }</code>.</p>
<p>The same process runs again, and <code>renamedObject</code> is properly created.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*OfKamMrGJLBIvY2WgQrlaA.png" alt="1*OfKamMrGJLBIvY2WgQrlaA" width="1600" height="599" loading="lazy"></p>
<p>This time, merging <code>acc</code> and <code>renamedObject</code> actually makes a difference.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*uMdN7mSsIhgvzJCceftUOw.png" alt="1*uMdN7mSsIhgvzJCceftUOw" width="1448" height="368" loading="lazy"></p>
<p>Run past this <code>debugger</code> to return that object, and you’re done!</p>
<p>Here’s the final output:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*TpcJHEG6MUxazCkNnCg6AQ.png" alt="1*TpcJHEG6MUxazCkNnCg6AQ" width="1600" height="454" loading="lazy"></p>
<p>Have fun renaming <strong>all the keys</strong>, until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
