<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hardik Thakar on Medium]]></title>
        <description><![CDATA[Stories by Hardik Thakar on Medium]]></description>
        <link>https://medium.com/@hardik-thakar?source=rss-497b3bc6f19d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y4u9OhwA99mvbmwfT_vLsw.jpeg</url>
            <title>Stories by Hardik Thakar on Medium</title>
            <link>https://medium.com/@hardik-thakar?source=rss-497b3bc6f19d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:28:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hardik-thakar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Boosting Your JavaScript Performance: PNPM, Deep Cloning, and JSON Circular Reference Solutions]]></title>
            <link>https://javascript.plainenglish.io/boosting-your-javascript-performance-pnpm-deep-cloning-and-json-circular-reference-solutions-47abdbb607d9?source=rss-497b3bc6f19d------2</link>
            <guid isPermaLink="false">https://medium.com/p/47abdbb607d9</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Hardik Thakar]]></dc:creator>
            <pubDate>Thu, 09 Mar 2023 20:11:47 GMT</pubDate>
            <atom:updated>2023-03-12T19:00:07.271Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tzWbXIDG100xQ-Lk" /></figure><p>In JavaScript programming, there are several techniques and libraries available to optimize performance, speed, and memory usage. In this article, we will discuss three such techniques: PNPM, deep cloning, and handling circular references in JSON objects. We will explore the use cases and benefits of each technique and recommend the best approach based on your specific project requirements.</p><h4><strong>PNPM </strong><a href="https://emojipedia.org/rocket/">🚀</a></h4><p>PNPM is a package manager for Node.js that aims to improve upon the shortcomings of traditional package managers like NPM and Yarn. It is said that it is nearly or more than 2 — 3 times faster than NPM and YARN (As mentioned on its <a href="https://pnpm.io/">official site</a>). Take this quiz to find out if PNPM is right for your project:</p><ol><li>Does your project have a large number of dependencies?</li></ol><ul><li>Yes</li><li>No</li></ul><p>2. Do you frequently encounter issues with disk space on your development machine?</p><ul><li>Yes</li><li>No</li></ul><p>3. Do you work on monorepo-style projects, where multiple packages are managed within a single repository?</p><ul><li>Yes</li><li>No</li></ul><p>Based on your answers, it looks like PNPM may be a good choice for your project! Here’s why:</p><ul><li>If you have a large number of dependencies, PNPM’s efficient use of disk space can save you a significant amount of storage on your development machine.</li><li>If you frequently encounter issues with disk space, PNPM’s global store can help alleviate those issues by sharing packages across all projects.</li><li>If you work on monorepo-style projects, PNPM offers better support for managing dependencies and sharing packages across multiple packages within the same repository.</li></ul><p>Keep in mind that PNPM may not be the best choice for every project. For smaller projects with few dependencies, NPM or Yarn may be sufficient. Ultimately, the choice of package manager depends on the specific needs and requirements of your project.</p><h4>Deep Cloning 📤</h4><p>Deep cloning is the process of creating a new object with the same values as the original object, while also creating new references for nested objects and arrays. This is an important technique in JavaScript programming, as it allows you to avoid unintentionally modifying the original object when working with its copy.</p><p>There are several ways to perform deep cloning in JavaScript. Here are some of the most popular methods:</p><p><strong>1. JSON.parse(JSON.stringify()):</strong> This is a quick and easy way to perform deep cloning, but it has some limitations. It doesn’t work with functions or symbols, and it can’t handle circular references.</p><p>JSON.parse(JSON.stringify()) involves converting an object to a JSON string using JSON.stringify(), and then parsing the JSON string back into a new object using JSON.parse(). This process can be slow and inefficient for large or complex objects, as it requires multiple iterations over the object and creates multiple copies of the data in memory.</p><figure><img alt="Deep Clonning using JSON.parse(JSON.stringify())" src="https://cdn-images-1.medium.com/max/1024/1*Xk1aHg5ugVXrlvbtJDxLaQ.png" /></figure><p><strong>2.</strong> <strong>_.cloneDeep():</strong> This method is part of the Lodash library and is widely used in JavaScript development. It’s capable of handling circular references, but it can be slower than other methods.</p><figure><img alt="Deep clone using cloneDeep" src="https://cdn-images-1.medium.com/max/1024/1*Q0pyN-NNbNh_8vUsGCkXIA.png" /></figure><p><strong>3.</strong> <strong>structuredClone():</strong> The structuredClone() method is a part of the HTML5 Web API that allows developers to clone an object in a structured way, including functions and other complex data types. However, this method has limitations that may affect its functionality for certain use cases. Some of the types that structuredClone() cannot copy include functions, object prototypes, DOM nodes, and property descriptors. Therefore, it’s important to be aware of these limitations when deciding which method to use for deep cloning objects in JavaScript.</p><blockquote>Note: You don’t need to import “<strong>structuredClone</strong>” it’s provided by native JS.</blockquote><figure><img alt="Deep clone using structuredClone" src="https://cdn-images-1.medium.com/max/1024/1*zhociXTe6LwNY40HZFcteQ.png" /></figure><p><strong>4. rdfc (</strong>Recursive Fast Deep Clone<strong>):</strong> This is a faster alternative to deep-clone that uses a recursive algorithm to quickly. The rfdc library is known for its speed and efficiency, making it a popular choice for deep cloning large objects in performance-sensitive applications.</p><p>However, It is having some limitations including a lack of support for functions and non-serializable data types, and an inability to preserve object prototypes or circular references.</p><figure><img alt="Deep clone using rdfc" src="https://cdn-images-1.medium.com/max/1024/1*UfALafvb7EvEarUW-AOSYw.png" /></figure><p>In terms of which method is best, it really depends on your specific use case. If you’re working in a browser environment and need to clone complex data types, <strong>structuredClone()</strong> might be the best choice. If you’re working with large data sets and need a fast way to compare objects for equality, <a href="https://www.npmjs.com/package/rfdc">rdfc</a> could be a good option. Overall, it’s important to consider the pros and cons of each method and choose the one that best meets your needs.</p><h4>Deal with circular references error 🤦🏻‍♂️</h4><p>JSON circular reference errors occur when an object contains a reference to itself or another object that ultimately references back to the original object. When you try to serialize an object with a circular reference using JSON.stringify(), the method goes into an infinite loop, eventually causing a stack overflow error.</p><p>One way to solve the JSON circular reference error without using any external library is to use the replacer parameter of JSON.stringify(). The replacer parameter is a function that can manipulate the JSON output during serialization. By using the replacer function to track circular references and replace them with a placeholder, you can avoid the infinite loop that causes the error.</p><p>Here’s an example of how to use the replacer parameter to handle circular references:</p><figure><img alt="Circular JSON error" src="https://cdn-images-1.medium.com/max/1024/1*HFTo8Hl6ov4oef2JedG8RQ.png" /></figure><p>In this example, the object obj contains a circular reference to itself. The replacer function checks if the current key is not empty and the current value is equal to the original object, and if so, returns the placeholder string &#39;[Circular]&#39;. Otherwise, it returns the original value.</p><p>The advantage of using this method is that it doesn’t require any external libraries and can handle circular references in a simple and straightforward way. However, this method can be time-consuming and may not be efficient for large objects with many circular references. In such cases, using a library like <a href="https://www.npmjs.com/package/json-stringify-safe">json-stringify-safe</a> can be a more efficient solution.</p><h4>Conclusion:</h4><p>By using the PNPM package manager, deep cloning techniques, and handling circular references in JSON objects, you can optimize your JavaScript programming to improve performance, speed, and memory usage. It’s important to consider the specific needs and requirements of your project before choosing the best approach. With these techniques and libraries, you can take your JavaScript programming to the next level and deliver optimized, high-quality code.</p><p>So that’s all for now. I hope you enjoyed this reading and may have learned something from this. Please leave a comment in case you have any concerns, do clap if you like so. Feel free to reach out to me through social media anytime.</p><p>If you haven’t yet read <a href="https://hardik-thakar.medium.com/basic-javascript-mistakes-and-best-practices-aa97ffc0e553"><strong>Common JavaScript Mistakes and Best Practices: Part 1</strong></a><strong> </strong>and<strong> </strong><a href="https://medium.com/javascript-in-plain-english/part-2-common-javascript-mistakes-and-best-practices-8d60b210617e"><strong>Common JavaScript Mistakes and Best Practices: Part 2</strong></a> then please go ahead and check them out.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em> community and follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em> and</em><strong><em> </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Learn how to build awareness and adoption for your startup with </em></strong><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47abdbb607d9" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/boosting-your-javascript-performance-pnpm-deep-cloning-and-json-circular-reference-solutions-47abdbb607d9">Boosting Your JavaScript Performance: PNPM, Deep Cloning, and JSON Circular Reference Solutions</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core JavaScript Warm Up]]></title>
            <link>https://javascript.plainenglish.io/core-javascript-warm-up-part-1-ac34934589d4?source=rss-497b3bc6f19d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac34934589d4</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hardik Thakar]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 18:31:03 GMT</pubDate>
            <atom:updated>2022-09-05T14:24:04.767Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: Strengthen your understanding of core JavaScript concepts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t1I10y6N9MEhiOTM" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we will see some JavaScript questions to warm up and strengthen your JavaScript core concepts.</p><p>We are starting it as a series where you will find different question lists along with its solution.</p><p>Let’s start with some amazing questions.</p><h4>Question 1</h4><p>What is the output of the following code?</p><pre><strong>function</strong> foo() { <br>  let a = 1;<br>  return <strong>function</strong> () { <br>    let b = 1; <br>    console.log(++a, ++b); <br>  }<br>} <br>const bar = <strong>foo();</strong></pre><pre><strong>bar();<br>bar();</strong></pre><p><em>Hint: It is a closure function</em></p><p><strong>Output:</strong></p><pre>2 2<br>3 2  </pre><p><strong>bar()</strong> represents the “<em>closure function”</em> defined in foo.</p><p>“<em>A closure always remembers its lexical scope.”</em></p><p>The value of ‘<em>a’</em> is always maintained and referenced by bar();</p><p>While for ‘<em>b’</em> it’s always initialized when the function calls and remains the same.</p><p>So every time it will initialize at 1 while the function is called.</p><h4>Question 2</h4><pre>let obj = {  <br>  foo: &quot;boo&quot;,<br>  a: <strong>function</strong> () {<br>    var b = this;<br>    console.log(this.foo);<br>    console.log(b.foo);<br>    (<strong>function</strong> () {<br>      console.log(this.foo);<br>      console.log(b.foo);<br>    })();<br>  }<br>} </pre><pre><strong>obj.a();</strong></pre><p><em>Hint: It is an IIFE function</em></p><p><strong>Output:</strong></p><p>IIFE is an independent function and for it ‘this’ would be a global variable.<br>So the output is:</p><pre><strong>boo<br>boo<br>undefined<br>boo</strong></pre><p><strong>Question 3</strong></p><p>Implement code for the given code example below.</p><p>(Make calc that can have these given functions which will return total as the value of a given operation)</p><pre>const result = calc.add(10).multiply(10).subtract(5).add(2);<br>console.log(result.total); // 97</pre><p><em>Hint: You can make a reusable function without any need of nesting functions to each other.</em></p><p><strong>Solution</strong></p><pre>const calc = {  <br>  <strong>total</strong>: 0,<br>  <strong>add</strong>: <strong>function</strong> (a) {<br>    this.total += a;<br>    return this;  <br>  },<br>  <strong>multiply</strong>: <strong>function</strong> (a) {<br>    this.total *= a;<br>    return this;  <br>  },<br>  <strong>subtract</strong>: <strong>function</strong> (a) {<br>    this.total -= a;<br>    return this;<br>  }<br>}</pre><p><strong>Question 4</strong></p><p>What is the output of the following code?</p><pre>let x = true;<br>let count = 0;</pre><pre>setTimeout(() =&gt; {<br>  x = false;<br>}, 2000);</pre><pre>setInterval(() =&gt; {<br>  if (x) {<br>    console.log(count++)<br>  }<br>}, 200);</pre><p>Hint: ‘x’ will be false after 2 Seconds till then setInterval can execute.</p><p><strong>Output:</strong></p><pre>0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8</pre><p>Because the counter will be incremented by 200ms. So, until the condition becomes <strong><em>false</em></strong><em>,</em> it will take 2000 ms. Hence, it will print a total of 9 times = 1800ms (each 200ms) and the last time, at 2000ms, the condition will be false.</p><p><strong>Question 5</strong></p><p>What is the output of the following code?</p><pre>var x = 21;<br>var fun1 = function () {<br>  console.log(x);<br>  var x = 20;<br>}</pre><pre>fun1();</pre><p><em>Hint: It is called hoisting in JavaScript</em></p><p><strong>Note:</strong> For those who are not familiar with hoisting in JavaScript, hoisting, as per <a href="https://developer.mozilla.org/en-US/docs/Glossary/Hoisting">MDN</a>, “refers to the process whereby the interpreter appears to move the <em>declaration</em> of functions, variables or classes to the top of their scope, prior to execution of the code.”</p><p><strong>Example of hoisting</strong></p><pre>console.log(x); // x is undefined because it is declared as &#39;var&#39;<br>var x = 10;</pre><pre>console.log(y);<br>let y = 10; // y will throw reference error because it is declared as &#39;let&#39; and &#39;let&#39; is hoisted in temporal deadzone</pre><pre>console.log(z);<br>const z = 10; // z also will throw reference error because it is declared as &#39;const&#39; and &#39;const&#39; is hoisted in the temporal deadzone</pre><p><strong>Output:</strong></p><p>It is neither 20 nor 21 but <strong>undefined</strong>.</p><p>Here, we want to assign x&#39;s value as 20 but before the assignment, <strong>it will be hoisted and the default value of var is undefined</strong>.</p><p>Many of you may ask it&#39;s var and since it has global access and x is 21 globally, then why it is not logged as 21?</p><p>The reason behind this is if you remove x = 20; from <strong>fun1()</strong>,<strong> </strong>then it will not be hoisted anymore. Hence, it will log as 21.</p><p>However, we declared it as 21 globally but we still hoisted it inside fun1(). That&#39;s why it was hoisted as undefined by default.</p><h3>Conclusion</h3><p>I hope you enjoyed reading and learning something new. We have started this series and will cover some more examples/questions that help JavaScript developers deep dive more into the core concepts and help brush up on advanced concepts.</p><p>I have written about common JavaScript mistakes and best practices <a href="https://hardik-thakar.medium.com/basic-javascript-mistakes-and-best-practices-aa97ffc0e553">part1</a> and <a href="https://hardik-thakar.medium.com/part-2-common-javascript-mistakes-and-best-practices-8d60b210617e">part2</a> that cover even more concepts.</p><p>Feel free to reach out to me for any suggestions, opinions, or queries by commenting. Thank you.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac34934589d4" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/core-javascript-warm-up-part-1-ac34934589d4">Core JavaScript Warm Up</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common JavaScript Mistakes and Best Practices]]></title>
            <link>https://javascript.plainenglish.io/part-2-common-javascript-mistakes-and-best-practices-8d60b210617e?source=rss-497b3bc6f19d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d60b210617e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Hardik Thakar]]></dc:creator>
            <pubDate>Tue, 15 Mar 2022 11:42:33 GMT</pubDate>
            <atom:updated>2022-09-05T17:17:09.558Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: Fundamental JavaScript programming skills that every JavaScript developer should be familiar with.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BupSKq1lJsZ613ZD" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks?utm_source=medium&amp;utm_medium=referral">Clay Banks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After the release of ES6, JavaScript developers adopted the ES6 standards and started using them in daily programming. But wait, aren’t we using some of these functionalities very frequently? Like spreading an object and making its copy to make sure we are not messing up mutating the original object’s value. But you know by spreading and cloning the object, you may or may not mutate the original’s value. Let’s look at an example.</p><h3><strong>1. Shallow Copy</strong></h3><p>You have an object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*RrjMk3Zf9vDDYuMs_7V7yg.png" /><figcaption>Original laptop object</figcaption></figure><p>Now here, we want a copy of this laptop object so any changes made to that copy will not change this original laptop object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*gIj_FxmXAGLNPtYLfgfLbw.png" /><figcaption>Making a clone of laptop object</figcaption></figure><p>Now change property in <strong><em>copyOfLaptop</em></strong> with <strong><em>copyOfLaptop.brand = “Dell”</em>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*F3UvXZ4iGznQPKQk1kGrsg.png" /><figcaption>after changing property in cloned object</figcaption></figure><p>And if you check the original laptop object, it will remain the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*RrjMk3Zf9vDDYuMs_7V7yg.png" /><figcaption>Original laptop object log after changing the brand value in cloned object</figcaption></figure><p>Seems expected? Maybe…</p><p>But guess what? If I change the value of the nested level object “<em>storage</em>” within <strong><em>copyOfLaptop</em></strong> (the cloned one), do you think it will mutate the original object?</p><p>Let us check.</p><p>We want to change the type and capacity of storage within <strong><em>copyOfLaptop.</em></strong></p><pre><em>copyOfLaptop.storage.type = “HDD”, <br>copyOfLaptop.storage.capacity = “500”</em></pre><p>It changed the value in <strong><em>copyOfLaptop</em></strong> as expected but what about the original object?</p><p>Let us check the original (laptop) object.</p><p>…And guess what?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*j-_39O8vCGO80W7P2JB6kg.png" /><figcaption>Log of the original object which mutates by its clone</figcaption></figure><p><strong>Reason? </strong>🧐</p><p>This happened because we used the spread operator for cloning an object. It basically cloned an entire object but it just prevents mutation from the first layer of JSON itself.</p><p>Meaning that if you changed the brand, model, os, or price (which is located at the first level of the object) in <strong><em>copyOfLaptop</em></strong><em>,</em> the original object will not mutate these values. But if you change values in a nested array or any deeper level other than the first level in the JSON, it will also manipulate the original JSON value simultaneously as both share the same address or location. This is called shallow copy.</p><p>👉 <strong>Better Solution</strong></p><p><strong>Deep copy/Deep Clone</strong></p><p>We can use deep cloning in any case where we are not sure if an object can have nested levels.</p><pre><strong><em>const copyOfLaptop = JSON.parse(JSON.stringify(laptop));</em></strong></pre><p>This will copy the entire object with a different address so it can never mutate the original JSON.</p><blockquote><strong><em>Note</em>:</strong> <em>Using</em> <strong><em>JSON.parse(JSON.stringify()) </em></strong><em>will not help you to deep copy any functions inside an object.</em></blockquote><h3><strong>2. for…each or findIndex or find?</strong></h3><p>Let us assume we have an array of objects called <strong><em>laptopList</em></strong> and want to manipulate OS value to “Windows 11” where brand = “DELL”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*hAE-BGeOtMxGKyW_pKgfHQ.png" /><figcaption>Array of objects</figcaption></figure><p>Now you may guess right what to use in this case. But in my code review, I have seen many developers using forEach or findIndex here to match the value. That’s the reason I included this example here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*T4__mLWI3R8qDmDNg8vmBA.png" /><figcaption>Iterate through the array to check the matching object using forEach</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*zOs4C2bBOdSq50WzG9p12g.png" /><figcaption>Iterate through the array using findIndex</figcaption></figure><p>👉 <strong>Better Solution</strong></p><p><strong>Using find</strong></p><p>First, just make sure that the matching value should be unique, meaning that only one object from an array is having the brand “Dell”. If so, you can just use the <strong>find </strong>iterator to iterate and manipulate the object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*I8R7scQbnA8VrJz31pCLMA.png" /><figcaption>Update values using the find inside an array</figcaption></figure><p>This will manipulate the original array’s specific object value where the brand is “Dell”.</p><h3><strong>3. Switch or Object?</strong></h3><p>Sometimes, we have a value to compare, and based on the chosen value, we have to provide its result.</p><p>We generally avoid if…else statements as it can cause multiple if…else statements and the code loses good readability and speed. So, we use switch-case statements to replace if..else. But what if you have multiple choices? The switch-case statement also being lengthy to read and understand.</p><p>Let’s have an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*tzahqNnttpzgR1iINaCCpw.png" /></figure><p>Here, it looks very lengthy, it takes an input and provides a matching output.</p><p>👉 <strong>Better Solution</strong></p><p>It&#39;s completely fine to use switch here but if you want a good readable code example that can solve this problem, you can use an object here to solve this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*A-9puKqJapAZAyQgYQ8XwQ.png" /><figcaption>Use object instead of the switch statement</figcaption></figure><p>I want to clarify that what to use totally depends on you. Using objects will not reduce the time complexity but the reason I mentioned this here is to improve your code readability.</p><h3>4. await or Promise.all?</h3><p>After ES6, we are very much used to the async-await syntax. We generally use it everywhere where the returning results are promises.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*YeStMjPu2VAp-WWS19tINw.png" /><figcaption>Using await for function execution</figcaption></figure><p>We have to take a random example where we assume that fetch will get the details of the book and calendar.</p><p>👉 <strong>Better Solution</strong></p><p>Use Promise.all in case the functions are not dependent on each other&#39;s output to process further. Using this is just not only good for readability but it allows the function to execute independently unlike the await syntax wherein one needs to wait until others&#39; execution is completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DxB15H4U_BOu11Ya4HYFMA.png" /><figcaption>Using Promise.all for function execution</figcaption></figure><p>So that’s it for now. I hope you enjoyed this reading and learned something from this. You can reach out to me anytime on social media for any suggestions or comments.</p><p>Also, if you have not read <a href="https://hardik-thakar.medium.com/basic-javascript-mistakes-and-best-practices-aa97ffc0e553"><strong>Common JavaScript Mistakes and Best Practices: Part 1</strong></a>, then please go ahead and check it out.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d60b210617e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/part-2-common-javascript-mistakes-and-best-practices-8d60b210617e">Common JavaScript Mistakes and Best Practices</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common JavaScript Mistakes and Best Practices]]></title>
            <link>https://javascript.plainenglish.io/basic-javascript-mistakes-and-best-practices-aa97ffc0e553?source=rss-497b3bc6f19d------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa97ffc0e553</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hardik Thakar]]></dc:creator>
            <pubDate>Sun, 07 Nov 2021 13:45:31 GMT</pubDate>
            <atom:updated>2022-09-01T10:18:17.124Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vj-eS6aoyMZlycPV" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">Kenny Eliason</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is for everyone, no matter if you are a beginner, an intermediate, or an advanced JavaScript developer. Here, we are discussing some of the very basic mistakes that many JavaScript developers are making.</p><p>There are some misconceptions about javascript. Especially for the iterators in JavaScript. Developers are very vague about choosing the iterators and forget the entire purpose of using them.</p><p>We will look into these mistakes in a minute but let’s talk about the main difference between a loop and the iterators.</p><p>Wait, what? Aren’t both the same?</p><p>You don’t categorize them as different usually, but there is a small catch there.</p><h3><strong>Loop vs. Iterator</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S0KfJtZsfjBZKSpr" /><figcaption>Loop Vs Iterator</figcaption></figure><p>In JavaScript, we get a variety of loops and iterators. We have <strong>for, while and do…while loops</strong> and we also have lots of <strong>iterators such as for-each, map, filter, reduce</strong>, etc.</p><p>Let’s talk a little bit more about the loops.</p><p>In a loop, we can determine the initial value for the loop from where it can start. Also, unlike the iterators, a loop allows you to determine the value of the increment variable that might help you to skip numbers of an element while using it.</p><p>Iterators just keep iterating each element of an array from start to end at a time and make appropriate operations according to the logic.</p><h3><strong>The Meaningless “Map”</strong></h3><p>Sounds weird?</p><p>We have multiple options for the iterator in the realm of JavaScript but they are all made for some kind of use-case.</p><p>I actually came across multiple code reviews where I have seen people using push() inside the map function. Let me show you an example to get a better understanding.</p><pre>const extraThirdArray= [];</pre><pre>postList.map(ele =&gt; {<br>   const showDetails = ele.showDetails; //Resulting in boolean value<br>   const postData = getPost(ele.id, showDetails);<br>   extraThirdArray.push(postData);<br>});</pre><pre>// <strong>getPost()</strong> will get post. If the second params showDetails is true then it will send some additional details to it otherwise it returns some basic details fot the post.</pre><p>There are a couple of more examples but I hope you can understand. There is no sense using push() within the map in this example.</p><p>Map returns a new array consisting of any value returned from the map. The map function itself maps the value and preserves it in its array. There is no meaning in creating an extra array and pushing elements within it while using the map.</p><p>The map function will do it for you. That is the main purpose of using the map.</p><pre>const postData = postList.map(ele =&gt; {<br>   return getPost(ele.id, ele.showDetails);<br>});</pre><p>or</p><p>Using shorthand 😍</p><pre>const postData = postList.map(ele =&gt; getPost(ele.id, ele &gt; 2));</pre><h3>Best Practices</h3><h4>1. Avoidable conditional statements</h4><p>Let’s check out some of the conditions that can easily be avoided.</p><p><strong>(i) Do we really need to check the condition for validating array length?</strong></p><pre>if(arr.length &gt; 0) {<br>  //Some logic<br>}</pre><p>Instead of unnecessary checks like if it’s greater than 0, we have a good way to deal with this.</p><p>👉 <strong>Better Solution</strong></p><pre>if(arr.length) {<br>  // Some logic<br>}</pre><p><strong><em>Why?</em> </strong>🧐</p><p>If there is a length that exists of the array except 0, it will be truthy and hence satisfies the if condition.</p><p><strong>(ii) Checking if the array has no length the following way?</strong></p><pre>if(arr.length &lt;=0) {<br>  //Some logic<br>}</pre><p>👉 <strong>Better Solution</strong></p><pre>if(!arr.length) {<br>  //Some logic<br>}</pre><p><strong><em>Why?</em> </strong>🧐</p><p>Arrays in JavaScript can never have a negative length. It can only be falsy if it&#39;s 0 and truthy vice-versa.</p><p><strong>(iii) Validating array length only to iterate over it?</strong></p><p>Many devs are using the <em>if condition</em> to check if the array has length and then afterward iterating over the array in order to not break the code.</p><pre>let postIds = [];<br>if(arr.length) {<br>   postIds = arr.map(e =&gt; e.id)<br>}</pre><p>👉 <strong>Better Solution</strong></p><pre>const postIds = (arr || []).map(e =&gt; e.id);</pre><p><strong><em>Why?</em> </strong>🧐</p><p>Assigning a default value as an empty array will prevent your code from being broken. In case there is any falsy value like undefined or null, it will fall back to the default value.</p><h4><strong>2. Don’t use the ternary operator unnecessarily</strong></h4><p>Sometimes, it’s required to set a variable to true in case a condition is satisfied and to set it false vice-versa. Developers use the ternary operator to achieve the same.</p><pre>const needPostDetails = post.created_at &gt; date ? true : false;</pre><pre>getPost(id, needPostDetails);</pre><p>👉 <strong>Better Solution</strong></p><pre>getPost(id, post.created_at &gt; date);</pre><p><strong><em>Why?</em> </strong>🧐</p><p>In this case, <strong><em>post.created_at &gt; date</em></strong> will return true if it is satisfied and false if it&#39;s not. You do not require a special condition like using the ternary operator to achieve this.</p><h4><strong>3. Want to remove keys from the object?</strong></h4><p>Well, deleting or removing keys from objects depends on the situation. If you want to manipulate the same object, you can go ahead and use the <em>delete</em> keyword as we usually do.</p><pre>const obj = {<br>   a:1,<br>   b:2,<br>   c:3,<br>   d:4,<br>   e:5,<br>   f:6,<br>   g:7<br>}</pre><pre>delete obj.e;<br>delete obj.f;<br>delete obj.g;<br>delete obj.a;</pre><pre>console.log(obj);</pre><pre>Output:</pre><pre><em>const obj = {</em><br>     b:2,<br>     c:3,<br>     d:4,<em><br>   }</em></pre><p>👉 <strong>Better solution</strong></p><pre>const {e,f,g,a, ...rest} = obj;</pre><pre>console.log(rest);</pre><pre>Output:</pre><pre><em>const obj = {</em><br>     b:2,<br>     c:3,<br>     d:4,<em><br>   }</em></pre><p><strong><em>Why? </em></strong>🧐</p><p>A better solution could be using the rest operator unlike using the <strong>delete</strong> keyword multiple times as you don’t need to use delete multiple times for the keys you want to delete. And using the rest operator will also not manipulate your existing object; instead, it provides a shallow copy of it.</p><h4><strong>4. Removing duplicate values from an array</strong></h4><pre>const arr = [1,3,4,2,3,1,3];<br>const uniqueValue = arr.filter((value, index, self) =&gt; {<br>    return self.indexOf(value) === index;<br>});</pre><pre>console.log(uniqueValue);</pre><pre>Output:<br>[1, 3, 4, 2]</pre><p>👉 <strong>Better Solution</strong></p><pre>const uniqueValue = [...new Set([...arr])];</pre><pre>console.log(uniqueValue);</pre><pre>Output:<br>[1, 3, 4, 2]</pre><p><strong><em>Why?</em> </strong>🧐<br>The better solution can be using a set in here. Set itself only contains the unique values. We can use its nature to achieve our goal.</p><p>I hope you enjoyed this reading and learned something from this. You can reach out to me anytime on social media for any suggestions or comments.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa97ffc0e553" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/basic-javascript-mistakes-and-best-practices-aa97ffc0e553">Common JavaScript Mistakes and Best Practices</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>