<?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 Edvinas Daugirdas on Medium]]></title>
        <description><![CDATA[Stories by Edvinas Daugirdas on Medium]]></description>
        <link>https://medium.com/@edvinas-daugirdas?source=rss-eaadefc65dd5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*VMT8E2zIeMksHP6MhZS7-w.jpeg</url>
            <title>Stories by Edvinas Daugirdas on Medium</title>
            <link>https://medium.com/@edvinas-daugirdas?source=rss-eaadefc65dd5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 23:29:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edvinas-daugirdas/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[Do you know everything about Map in JavaScript?]]></title>
            <link>https://edvinas-daugirdas.medium.com/do-you-know-everything-about-map-in-javascript-d94bfc6d8926?source=rss-eaadefc65dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d94bfc6d8926</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Edvinas Daugirdas]]></dc:creator>
            <pubDate>Mon, 28 Jun 2021 12:51:12 GMT</pubDate>
            <atom:updated>2021-06-28T17:13:49.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WLBZGK0cjSHiSM49" /><figcaption>Photo by <a href="https://unsplash.com/@marjan_blan?utm_source=medium&amp;utm_medium=referral">Marjan Blan | @marjanblan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>2015 was a great year for JavaScript — the language received a much-awaited significant update, by the name of ECMAScript 6 (a.k.a. ES6, a.k.a. ECMAScript 2015 ¯\_(ツ)_/¯), the first update to the language since ES5 was standardized back in 2009. Among many features four newly formed data structures were introduced: Map, Set , WeakMap , WeakSet .</p><p>Surprisingly to me, six years have already passed since ES6 initial release and after all that time some of these data structures still feel so new and fresh. With all of that being said, feeling the pressure of my ever-growing impostor syndrome, I’ve decided to refresh my memory on one of these lovely structures — Map . And if you’re in the same boat as me (don’t worry, there’s nothing wrong with you) let’s explore together what this thing can do.</p><h4>Same same, but different, but still the same</h4><p>If you’ve been on the internet long enough you’ve probably encountered the meme before and it kind of relates to Map in a way. Map is quite similar to the well-known Object that you’ve been using for ages. So what is Map after all?</p><p>It’s a data structure that holds key-value pairs, just like our friend Object . Of course it has it’s fair share of differences, but the similarity is so apparent that historically Object has been used as Map (there were no other alternatives). Just look how readable and understandable this code snippet is when you have that mental model in your head:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecd69f30cd933f3bf89613b0e5bdb8d7/href">https://medium.com/media/ecd69f30cd933f3bf89613b0e5bdb8d7/href</a></iframe><p>Sure, the API is different, but I’m pretty sure that you understand what this code does and what its purpose is by just looking at it. Essentially what we’re doing here is creating a new Map instance, setting some values, deleting them, checking the size, your standard stuff.</p><p>Instead of setting values as properties as we would on an Object (which you can also do on Map, but please don’t do that) we use this nifty API that Map gives us. This opens up some new capabilities like checking the size of an instance, like we did on line 9 with pokemons.size , which we can not do on an Object instance.</p><p>You could also initialize a Map with pre-existing values if you wanted to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b89b9448df904a92636082719749a2a/href">https://medium.com/media/3b89b9448df904a92636082719749a2a/href</a></iframe><p>I’m not going to bore you by describing every method that exists on Map, but if you’re interested here’s a good place to start: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#instance_methods">Map, Instance methods — JavaScript | MDN </a>.</p><h4><strong>But different…?</strong></h4><p>Now that we know what Map is and how it functions let’s explore the more interesting and impactful differences that it has compared to an Object .</p><p><strong>Key types and accidental keys</strong></p><p>Although it make come as a surprise keys of an Object are always either a String or a Symbol . What does that mean for us? Well, for example, that means that the Object keys can not be a Number. In the following code snippet obj[1] key will be coerced to a String .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3719a2d7ecbc75afa2a158b855164c68/href">https://medium.com/media/3719a2d7ecbc75afa2a158b855164c68/href</a></iframe><p>That’s not the only limitation when it comes to keys in an Object , you might accidentally override a default Object key, like toString method for example. To be honest I can’t recall a situation where I would run into this particular “problem”, but I guess technically it could be an issue.</p><p>These problems don’t exist on a Map . It does not give a single flying duck what its key is. Want to give it a Number as a key? Yep.</p><p>Maybe a Boolean , Function or even an Object ? No problem what so ever.</p><p>This type of functionality is quite useful when you’re not sure what type of keys you will be using. If the key is specified from an external source (say a user input or an API call response) Map is a good candidate to solve that problem. Or if you just want to use Number , Function or whatever type as a key instead of String , Map got you covered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed3e31fae684d280008424823450b338/href">https://medium.com/media/ed3e31fae684d280008424823450b338/href</a></iframe><p><strong>Order and iteration</strong></p><p>Object is a nonordered data structure, meaning that it does not care about the sequence in which your key-value pairs were entered. Well, it actually does have an “order” now, but it’s hard to understand, there’s tons of rules and it’s just better not to rely on it, since the possibility of introducing a bug is relatively high.</p><p>It also does not implement an iteration protocol, meaning that objects are not iterable using for...of statement. You can get an iterable object using Object.keys or Object.entries though.</p><p>On the other hand Map is ordered, it remembers the original sequence of your key-value pairs and it also plays nicely with the iteration protocol. Cool. Let’s take a look how that might be useful.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/170533755abf24d9bb55569ac59a9cc8/href">https://medium.com/media/170533755abf24d9bb55569ac59a9cc8/href</a></iframe><p>Now you might be thinking: “Who cares what order these will be printed out?”. Little did you know that John and Jane are low-key maniacs and they like to be first everywhere. In all seriousness though maybe this is not the best example, but hopefully it conveys the concept. If anyone sees an obvious use case where order is important and it’s related to pokemons, let me know.</p><p>You could even use other methods that exist on Map and iterate through them in the same fashion:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c2b8ad9deddc91aee6adf1450bf2cb3/href">https://medium.com/media/8c2b8ad9deddc91aee6adf1450bf2cb3/href</a></iframe><p>You could even forEach this bad boy if you wanted to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51bca5099e503b438ae339fbe45bb7c1/href">https://medium.com/media/51bca5099e503b438ae339fbe45bb7c1/href</a></iframe><p>I want to reiterate that we could achieve almost the same functionality using a plain old Object , but if we care about the order of our values Map is definitely the way to go.</p><p><strong>Performance</strong></p><p>Map has some distinct performance improvements when it comes to frequent additions and removals of key-value pairs unlike Object. If you ever find yourself in a position where you need to get some performance gains on that front Map just might be your new friend that comes to save the day.</p><p><strong>Serialization and parsing</strong></p><p>This might be a bummer for some of you, because Map does not offer any serialization or parsing capabilities. That means that if we use JSON.stringify or JSON.parse we’ll not get much.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02bda8e06cc54636e52ba311a58ead00/href">https://medium.com/media/02bda8e06cc54636e52ba311a58ead00/href</a></iframe><p>You could create your own serialization and parsing if you wanted to of course, <a href="https://stackoverflow.com/questions/29085197/how-do-you-json-stringify-an-es6-map">here’s how you can do it</a>.</p><p><strong>Key equality</strong></p><p>Map uses a <em>SameValueZero </em>algorithm. OK, but what does that mean? Let’s start by looking which equality algorithms currently exist in JavaScript:</p><ul><li>Abstract Equality Comparison (==)</li><li>Strict Equality Comparison (===)</li><li>SameValueZero (the one that Map uses)</li><li>SameValue (Object.is)</li></ul><p>I’m fairly sure that you’ve definitely encountered == or === in the wild. Object.is is something that I personally haven’t seen that often, it’s a bit out of topic, so in case you’re interested you can read more <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is">here if you want.</a></p><p>What we’re curious about is <em>SameValueZero </em>and why it’s used in Map operations. To gain some instant familiarity just imagine that it’s the same as === only with some additional quirks.</p><p><em>Quirk no. 1: </em>it treats signed zeroes as the same value. That means that +0 and -0 is the same in Map eyes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2534ebc97c284e4717e914ede1c1d9a/href">https://medium.com/media/e2534ebc97c284e4717e914ede1c1d9a/href</a></iframe><p>The only explanation that I could find why this is important is because -0 could easily sneak into your code via an arithmetic operation, but you almost always want -0 to be treated as 0 .</p><p><em>Quirk no. 2: </em>it treats NaN as equal to other NaN values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d323607125ebae25dacb1c968d00c2b4/href">https://medium.com/media/d323607125ebae25dacb1c968d00c2b4/href</a></iframe><p>This one is kind of straightforward, as we don’t want to have <em>distinct </em>NaN values.</p><p>That’s all folks. If you’ve made it until the end I just wanna say thanks, that really warms my heart ❤️</p><p>Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d94bfc6d8926" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s the difference between never and void in TypeScript?]]></title>
            <link>https://medium.com/swlh/whats-the-difference-between-never-and-void-in-typescript-16f6629bfcdc?source=rss-eaadefc65dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/16f6629bfcdc</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Edvinas Daugirdas]]></dc:creator>
            <pubDate>Thu, 06 Feb 2020 06:31:45 GMT</pubDate>
            <atom:updated>2020-02-11T17:17:45.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IrQD_KiTGj5MxaBl" /><figcaption>Photo by <a href="https://unsplash.com/@insolitus?utm_source=medium&amp;utm_medium=referral">Rowan Heuvel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re still somewhat new to TypeScript or just haven’t had the time to fully analyze it’s basic types you may have noticed that some of them may look a bit more daunting then others. Sure, it’s quite easy to understand what a number or a string is, but never and void ? Not so much.</p><p>The two types might look similar at first glance, but they are separate for a reason. To completely understand their differences let’s dive into them one by one and explore what their purpose is in TypeScript.</p><h3>void</h3><p>You’ve probably seen this type around and it’s usually used as a return type of functions which do not have a return value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*k8piUGX8pAguVL49CutMiQ.png" /></figure><p>In JavaScript a function that doesn’t return anything explicitly returns undefined by default. These functions are inferred by TypeScript to have return type of void.</p><p>You can think of void as a little opposite of any: the absence of having any type at all. Declaring variables as void is not very useful though because you can only assign undefined or null if --strictNullChecks is not specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*bwIproM7v9-EaPFINC5uDw.png" /></figure><h3>never</h3><p>never type is a bit more difficult to fully understand in my opinion, but the basic idea is quite simple. The type represents types of values that never occur. For example it can be used with functions that never return or with functions that that always throw an exception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*qwVDCAx9XH--d2ya0N2Vng.png" /></figure><p>never is also inferred by TypeScript when narrowed by type guards that can never be true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*Z-TXnPIzPP_H55KkFATbFA.png" /></figure><p>Another great common use case is to use never with conditional types to exclude undesired types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*niEMHMV2LmrNmowCwHrWHQ.png" /></figure><p>One edge case that you should be aware of though is that TypeScript infers function declarations and function expressions with arrow functions differently. If you’re interested why there’s a <a href="https://stackoverflow.com/questions/40251524/typescript-never-type-inference">great resource on StackOverflow.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*SC9EXlDgLCu8p6TkwUxJIw.png" /></figure><h3>Conclusion</h3><p>With solid grasp of what never and void types are we can conclude that the types are quite different. void is used whenever a function does not return anything explicitly (usually that means it returns undefined implicitly) and never whenever a function never returns at all.</p><p>Hope you’ve learnt something new, thanks for reading! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16f6629bfcdc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/whats-the-difference-between-never-and-void-in-typescript-16f6629bfcdc">What’s the difference between never and void in TypeScript?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with multiple Promises in JavaScript]]></title>
            <link>https://medium.com/swlh/dealing-with-multiple-promises-in-javascript-41d6c21f20ff?source=rss-eaadefc65dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/41d6c21f20ff</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Edvinas Daugirdas]]></dc:creator>
            <pubDate>Wed, 06 Nov 2019 06:23:49 GMT</pubDate>
            <atom:updated>2019-11-06T11:18:59.254Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xa6xelcstPKoGW_f" /><figcaption>Photo by <a href="https://unsplash.com/@amseaman?utm_source=medium&amp;utm_medium=referral">Andrew Seaman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects">ECMAScript 2015</a> introduced Promises into JavaScript world — the days of callback hell were over. We adopted them quickly and soon you could see promises almost in every new code base.</p><p>If you’re like me you’re working with promises on a daily basis — you’re fetching resources, maybe you’re dealing with a library that uses them or maybe you have your own little functions that need to handle asynchronous operations.</p><p>Usually, we only need to handle only one asynchronous operation, rarely do we encounter such circumstances that we need to use multiple promises. And to be honest, it can be a bit tricky if you’re dealing with that for the first time as there are several different ways of doing that. Let’s examine what techniques and methods we can use to make our lives a bit easier.</p><h3>Promise.all()</h3><p><strong>Promise.all() </strong>takes an iterable (such as Array) and returns a single promise that resolves when all of the promises have resolved. Let’s see it in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*dkJK5Xe03JAMtiR9rA-r0g.png" /></figure><p>We created two promises: <strong>promise1 </strong>resolves immediately with a string of “Hello” and <strong>promise2 </strong>resolves after a second with the string of “World”. Easy enough. It’s really important to note that there is no ordering in execution of the given promises — in some computers they may be executed in parallel, but on others they may be executed serially.</p><p>Keeping that in mind we can see how this method can be helpful, for example, if we need to fetch data from different points and they’re not dependent on each other (that means that we’re not interested in the sequence of execution) we can use <strong>Promise.all() </strong>to do that. But, there are some things that we need to keep in mind when using this method.</p><p><strong>Promise.all() </strong>has a fail-fast behavior. It means that if one of the promises is rejected then the promise returned from <strong>Promise.all() </strong>is rejected as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*to2uzXZGHczUK8yqdp9gJA.png" /></figure><p>We’ve added a new promise <strong>promise3 , </strong>which is being rejected after two seconds. As you can see as soon as we’re hitting reject <strong>Promise.all() </strong>will also reject immediately. It doesn’t matter if the other promises would have resolved successfully and in what order the actions happened, one reject is all that it takes. But, we can change this behavior by handling possible rejections like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*AK2j7EvhfYA2prpUMbe-gw.png" /></figure><p>We’re using almost exactly the same code as above, the only difference is that we’ve added <strong>map(p =&gt; p.catch(e =&gt; e)) </strong>after <strong>Promise.all() , </strong>where we’re mapping possible rejections<strong>. </strong>We could also done it inline (since we know which promise is rejecting), but that probably won’t be the case in a real world scenario:</p><pre><strong>Promise.all([promise1, promise2, promise3.catch(e =&gt; e)])</strong></pre><p>But what if I told that there might a better way of handling this sort of scenario? Let’s talk about <strong>Promise.allSettled() .</strong></p><h3>Promise.allSettled()</h3><p><strong>Promise.allSettled() </strong>is really similar to <strong>Promise.all() . </strong>It also takes an iterable and returns a promise that resolves after all of the given promises either have resolved or rejected, with an array of objects which describe the outcome of each promise.</p><p>In simple words, it’s <strong>Promise.all() </strong>without fail-fast behavior and also a bit different return value. But why the different return value? Well, for us to understand whether the provided promise was rejected or resolved a simple value is usually not enough. That’s why instead of just returning the value from a promise <strong>Promise.allSettled() </strong>returns an object. Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*4kstbTTTj9gXvgAaMDp3XA.png" /></figure><p>Again we’re using the same example as above, the only different is that we’ve replaced <strong>Promise.all()</strong> with <strong>Promise.allSettled()</strong>. We don’t need to catch possible errors anymore and the returned value has now become an array of objects with possible values of:</p><pre><strong>{ status: &#39;fullfilled&#39;, value: &#39;value&#39; }<br>{ status: &#39;rejected&#39;, reason: &#39;reason&#39; }</strong></pre><p>By using status we can explicitly tell whether the promise has been rejected or resolved.</p><p>Unfortunately we can’t simply use <strong>Promise.allSettled()</strong> in production as of right now, as it’s currently in <a href="https://github.com/tc39/proposal-promise-allSettled">stage 4 draft mode</a>. I’m pretty sure you can find a polyfill if you want to (although it’s reasonably easy to it write yourself, since we know how it works). It will become a standard feature of next iteration of ECMAScript and is expected to be <a href="https://github.com/tc39/proposals/blob/master/finished-proposals.md">publicized in 2020</a>. It’s also worth mentioning that there are already <a href="https://caniuse.com/#search=allSettled">some browsers that are supporting it</a>.</p><h3>Promise.race()</h3><p><strong>Promise.race()</strong> is a bit different although very similar to previous methods that we’ve discussed. It also takes in an iterable as an argument and returns a promise that either resolves or rejects as soon as one of the promises are either resolved or rejected. Example when both of the promises are resolved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*4ukdvbh9cHZE2-w75cNzYQ.png" /></figure><p>We provide two promises, <strong>promise1 </strong>and <strong>promise2</strong> — <strong>promise1 </strong>resolves after 2 seconds and <strong>promise2 </strong>resolves after 3 seconds, so naturally only see “First promise” logged out, since it was resolved first. This works the same with rejections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*GwPW2VNTzSg7cdHYJVAxzw.png" /></figure><p>Almost identical example as above, but now we’re rejecting instead of resolving the first promise.</p><p>As for real world scenarios imagine you have a request/computation that might take really long time to resolve and you want to wait maximum of 5 seconds. You can leverage <strong>Promise.race() </strong>and provide both the request/computation and a separate promise that rejects the promise after 5 seconds. If you don’t get the expected result you know that the task didn’t resolve in a timely fashion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*Fm1Ho_zhWc201Q2Kig0S5Q.png" /></figure><h3>loops and async/await</h3><p>Remember how we’ve talked about <strong>Promise.all()</strong> and how it doesn’t respect the order of execution? If that’s important for your use case <strong>for...of</strong> loop is a great way to go. Let’s look at an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*evvwVME0U0M8SGA7OK6VKQ.png" /></figure><p>It’s really similar to what we’ve looked at previously. We’re iterating over three promises, awaiting for the result and logging the message out. You could also use a basic <strong>for</strong> loop, but I like <strong>for…of</strong> more because it looks a bit cleaner.</p><p>We can also leverage <strong>map </strong>to create an array of promises and use <strong>Promise.all()</strong> to deal with. It’s also possible to manipulate the return data if you want!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*WgwscOJCVoS_G33TW3iEbg.png" /></figure><p>Here we’re creating promises on the fly with a helper function <strong>createPromise , </strong>mapping them into an array called <strong>greetingPromises </strong>and awaiting inside to manipulate the data from the promise. This is really cool and we could use this technique in a variety of scenarios, for example processing responses of multiple requests to the server.</p><p>One thing that I should mention is that I don’t recommend using <strong>async/await </strong>with <strong>forEach</strong>, as it’s not promise-aware, it won’t wait for execution to end and will just jump unto the next iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*Qo0bqp9l1ZB5tVL19z3hDA.png" /></figure><p>As you can see <em>start </em>and <em>finish </em>messages are logged out first, even though we’re waiting for inside the <strong>forEach </strong>loop for the message.</p><p>Thanks for reading, I hope you’ve learnt something new!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41d6c21f20ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/dealing-with-multiple-promises-in-javascript-41d6c21f20ff">Dealing with multiple Promises in JavaScript</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 things you might not know you can do in React]]></title>
            <link>https://medium.com/swlh/4-things-you-might-not-know-you-can-do-in-react-be234bdcab1b?source=rss-eaadefc65dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/be234bdcab1b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Edvinas Daugirdas]]></dc:creator>
            <pubDate>Sun, 13 Oct 2019 05:38:35 GMT</pubDate>
            <atom:updated>2019-10-13T13:36:43.637Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hpmw9LIPH4C9kld6" /><figcaption>Photo by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>React has seen remarkable growth and adoption since it’s initial release in 2013. <a href="https://insights.stackoverflow.com/survey/2019#most-loved-dreaded-and-wanted">Being the most loved and most wanted web library for developers</a> it comes as no surprise that it is one of the most popular JavaScript libraries at the moment.</p><p>One of the things that makes React so attractive to me is that despite using it for numerous years you can still discover new techniques and tricks. And although the techniques that I’m going to introduce will probably not be used very often, nevertheless, they’re quite powerful when used in a right scenario. So without further ado, here are four things that you you might not know you can do in React.</p><h4>1. Forcing a component remount using key property</h4><p>We all know that we need to include <strong>key </strong>property when creating lists of elements in React. But why do we need to use it in the first place? Because <strong>key </strong>helps <a href="https://reactjs.org/docs/lists-and-keys.html#keys">identifying which items have changed, were added or removed.</a></p><p>Imagine you have an array of strings <strong>[&#39;Dog, &#39;Cat&#39;, &#39;Owl&#39;]</strong> and you want to render it’s items inside a component. After your initial render you’ve decided that you want to add an additional item to the beginning of your array, basically pushing all other three elements to the end. In a world without a <strong>key </strong>property React would mutate the first three items instead of keeping it, although they didn’t change, they just need to switch places. That’s where <strong>key </strong>comes in. <a href="https://reactjs.org/docs/reconciliation.html#recursing-on-children">When items have keys React can use it to understand what actually happened and not re-render each and every item.</a></p><p>Having all of that in mind we can also use the <strong>key</strong> property in a bit of a different scenario. Since it basically can tell that the component identity has changed we have the power to re-instantiate it whenever we want. Here’s a simple counter example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3470e47afc495d1a67b60bbc66d2b455/href">https://medium.com/media/3470e47afc495d1a67b60bbc66d2b455/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Faffectionate-hofstadter-z49v3%3Ffontsize%3D14&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Faffectionate-hofstadter-z49v3%3Ffontsize%3D14&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fz49v3%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbd1a5e4d0c11de6c8feebb74210f27a/href">https://medium.com/media/bbd1a5e4d0c11de6c8feebb74210f27a/href</a></iframe><p>By leveraging the <strong>key</strong> property from the parent <strong>App </strong>component we could easily reset the state inside the <strong>Counter </strong>component. This trick comes really handy sometimes, although you should be aware of performance implications (as discussed above).</p><h4>2. Passing components as props</h4><p>This one is definitely not that difficult as the first tip, it’s quite easy and straight-forward to be honest, although I don’t see it used that often.</p><p>React recommends using composition instead of inheritance to reuse code between components and for that we have <strong>props.children</strong>. But sometimes you need multiple <strong>props.children</strong> so to speak, so you can create your own convention of passing components. You might find some references to this as using <a href="https://twitter.com/dan_abramov/status/958728081287589889?lang=en">“slots”</a> or <a href="https://reactjs.org/docs/composition-vs-inheritance.html#containment">“holes”</a> in your component. Let’s take a look into a simple <strong>Layout </strong>component example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b83d4cee7656197d0790c07b5b49f6f3/href">https://medium.com/media/b83d4cee7656197d0790c07b5b49f6f3/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fancient-frog-ori2x%3Ffontsize%3D14&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fancient-frog-ori2x%3Ffontsize%3D14&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fori2x%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/6357f95874aaac9eefdfa7184a5068dd/href">https://medium.com/media/6357f95874aaac9eefdfa7184a5068dd/href</a></iframe><p>This makes <strong>Layout </strong>really flexible, because we can change left, right panel components on the fly, we can create parent layout components with the slots already attached or you can even inline JSX right into it and it will work just fine.</p><h4>3. Functional updates using useState</h4><p>Let’s examine our first <strong>Counter </strong>example a bit: we’re using <strong>useState </strong>to manage the state of the counter and updating it using our current value. This works perfectly fine in our little example, but what would happen if we would want to add a number each second? We could do something like this:</p><pre>React.useEffect(() =&gt; {<br>  let counterInterval = setInterval(() =&gt; {<br>    setCount(count + 1)<br>  }, 1000)</pre><pre>  return () =&gt; clearInterval(counterInterval)<br>}, [])</pre><p>With this setup our counter does update, but it only updates to 1 and stops there (take a look into the console, you’ll see what <strong>count </strong>value is inside <strong>setInterval </strong>function).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fserene-jennings-r0wxv%3Ffontsize%3D14&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fserene-jennings-r0wxv%3Ffontsize%3D14&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fr0wxv%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9b869d35d532838e315068722594f6e/href">https://medium.com/media/f9b869d35d532838e315068722594f6e/href</a></iframe><p>Why? Well, closures. Because <strong>count </strong>is being captured on it’s initial value in <strong>setInterval</strong>, which is 0, we’re stuck at 1. We could fix this problem by specifying <strong>count </strong>inside <strong>useEffect </strong>dependency array, but that would mean that we would need to clear the interval each time the value changes, which in short is not ideal. But, we could also use a functional update by using the previous state. The change is rather simple, but it does solve our problem:</p><pre>let counterInterval = setInterval(() =&gt; {<br>  setCount(count =&gt; count + 1)<br>}, 1000)</pre><p>Now we don’t need to specify <strong>count </strong>as a dependency and the issue is gone! Every time you need to use a previous value of your state, remember that you can pass a function to your state updating function.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fbeautiful-stonebraker-6s3kw%3Ffontsize%3D14&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fbeautiful-stonebraker-6s3kw%3Ffontsize%3D14&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F6s3kw%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/47640c056b6aa3b429ebc3f958e6e0e0/href">https://medium.com/media/47640c056b6aa3b429ebc3f958e6e0e0/href</a></iframe><h4>4. Lazy state initialization</h4><p>Since we’re already examining some rarely used <strong>useState </strong>functionality I thought it would be good to mention that you can create expensive objects lazily with it as well.</p><p>There are a couple of ways of creating expensive objects lazily using hooks. You can use <strong>useMemo </strong>, the more popular choice from what I’ve seen, which caches your calculation by using the dependency array (looks really similar to <strong>useEffect</strong>).</p><pre>const value = useMemo(() =&gt; calculation(a, b), [a, b]);</pre><p>Now this is a really good way of lazily creating an object if you have dependencies on your calculation. <a href="https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily">But, it only serves as a hint and doesn’t guarantee that the computation won’t <strong>re-run</strong>.</a></p><p>However, if you don’t have dependencies and only want to create the object once you can pass a function to <strong>useState. </strong>Let’s take a look how this might look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50b90f7d06958b53c3eccbd1d4b112d3/href">https://medium.com/media/50b90f7d06958b53c3eccbd1d4b112d3/href</a></iframe><p>This is something that you probably won’t use that often, but I still think that it’s worth a mention.</p><p>Hopefully you’ve found out something new today. If this was new to you I do highly recommend diving into the provided examples yourself. Thanks and good luck on your React projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be234bdcab1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/4-things-you-might-not-know-you-can-do-in-react-be234bdcab1b">4 things you might not know you can do in React</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spread operator and shallow copying in JavaScript]]></title>
            <link>https://edvinas-daugirdas.medium.com/spread-operator-is-shallow-cloning-properties-in-javascript-5ba89d0495a5?source=rss-eaadefc65dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ba89d0495a5</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Edvinas Daugirdas]]></dc:creator>
            <pubDate>Thu, 03 Oct 2019 15:46:47 GMT</pubDate>
            <atom:updated>2019-10-03T18:05:37.216Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPBQZoS_vQibTROLuYHhzQ.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/@kevin-ku-92347">Kevin Ku</a> on <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><p>The introduction of spread operator into JavaScript made merging/copying objects really easy and if you’re like me you’ve been using it quite often. But, there is one little thing that is really important: spread operator is <strong>shallow copying properties.</strong></p><p>If you’ve never seen spread operator in work here’s an example:</p><pre>const obj1 = { x: 10 }<br>const obj2 = { y: 20 }<br>const mergedObj = { ...obj1, ...obj2 }</pre><pre>console.log(mergedObj) // { x: 10, y: 20 }</pre><p>The two objects <strong>obj1 </strong>and <strong>obj2 </strong>are merged together into <strong>mergedObj </strong>copying all of their properties. Let’s see what happens if we change a property on <strong>mergedObj.</strong></p><pre>mergedObj.x = 20</pre><pre>console.log(mergedObj) // { x: 20, y: 20 }<br>console.log(obj1) // { x: 10 }</pre><p>The change only affected <strong>mergedObj </strong>and didn’t change anything on <strong>obj1</strong>. Cool. Now let’s change <strong>obj1 </strong>a little bit and instead of <strong>x</strong> property being a number let’s make it an object.</p><pre>const obj1 = { x: { count: 10 } }<br>const obj2 = { y: 20 }<br>const mergedObj = { ...obj1, ...obj2 }</pre><pre>console.log(mergedObj) // { x: { count: 10 }, y: 20 }</pre><p>Once again we’ve got a merged object with all of <strong>obj1 </strong>and <strong>obj2 </strong>properties copied. But now if we make a change to <strong>mergedObj.x</strong> something interesting happens:</p><pre>mergedObj.x.count = 20</pre><pre>console.log(mergedObj) // { x: { count: 20 }, y: 20 } console.log(obj1)// { x: { count: 20 } }</pre><p>Even though we didn’t touch <strong>obj1 </strong>it’s property <strong>x</strong> value has been changed! That’s because spread operator didn’t create a new object {count: 20} on <strong>mergedObj</strong>, it copied it by reference. You can probably see how dangerous this can be. Imagine we had an array of objects, made a copy of it with the help of spread operator and changed an item inside of it:</p><pre>const obj1 = { x: 10 }<br>const obj2 = { y: 20 }<br>const arr = [obj1, obj2]</pre><pre>const arrClone = [...arr]<br>console.log(arrClone) // [ { x: 10 }, { y: 20 } ]</pre><pre>arrClone[0].x = 20</pre><pre>console.log(obj1) // { x: 20 }<br>console.log(arr) // [ { x: 20 }, { y: 20 } ]</pre><p>So next time you’re using spread operator remember that it does not create a deep clone, but a shallow one! If you want to learn more about spread syntax and how it works read more <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ba89d0495a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning modern JavaScript through Selection sort]]></title>
            <link>https://medium.com/swlh/learning-modern-javascript-through-selection-sort-13db14cbd52e?source=rss-eaadefc65dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/13db14cbd52e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Edvinas Daugirdas]]></dc:creator>
            <pubDate>Sun, 29 Sep 2019 05:40:17 GMT</pubDate>
            <atom:updated>2019-09-30T18:38:13.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHgLhRImp4ufuU8jAlNcxQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@markusspiske">Markus Spiske</a> on <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><p>A few days ago I was going through some old files on my computer and I’ve found, to my surprise, a lot of old code that I’ve written way back. One of the folders that I’ve found was filled with files of different algorithms and when I’ve opened one of them I’ve noticed a syntax that I haven’t used in quite a while — it was good old ES5 JavaScript. And I thought it would be really interesting to take one of them and introduce some modern JavaScript.</p><p>I’ve picked a really basic sorting algorithm — selection sort, that way we can focus more on code itself and not the idea behind it <br>(although if you’re not familiar with selection sort you’ll benefit from this article even more!).</p><p><strong>Note: </strong>The changes that we’re making do not make the code “better” or “worse” necessarily, the point of the article is to introduce new syntax and new concepts, so some of the updates might look a bit arbitrary.</p><h3>Selection sort</h3><p>If you’re comfortable with selection sort you can definitely skip this section, otherwise I highly recommend reading it. The algorithm itself is fairly uncomplicated. The idea behind selection sort is finding the minimum element and putting it into the beginning of the array by swapping the current iterative value with the minimum value. With each and every iteration we’re getting almost two separate sub arrays, sorted and unsorted. Let’s look at an example with the following array:</p><pre>array = [50, 20, 3, 6, 12]</pre><p>Our first iterative value will be 50 and we want to find the lowest value forward (in our case it’s 3) and swap it 50. After the first iteration our array should look like this:</p><pre>[<strong>3</strong>, 20, <strong>50</strong>, 6, 12] // Two swapped values are 50 and 3</pre><p>That gives two partitions of the array, sorted and unsorted. Let’s do another iteration, that way it will be easier to see those partitions. Our iterative value will be 20 and the lowest value forward would be 6. That’s the swap that we make.</p><pre>array = [3, <strong>6</strong>, 50, <strong>20</strong>, 12] // Two swapped values are 20 and 6</pre><p>After two iterations we can see that we have two partitions of the array, one sorted and one unsorted. The numbers in bold are sorted:</p><pre>array = [<strong>3</strong>, <strong>6</strong>, 50, 20, 12] // 50, 20, 12 is left unsorted</pre><p>Then we repeat the iteration one more time. Our iterative element is 50 and the lowest value forward is 12, make the swap:</p><pre>array = [3, 6, <strong>12</strong>, 20, <strong>50</strong>] // Two swapped values are 50 and 12</pre><p>And at this point our iterative element is 20, which is the lowest value already, so we don’t need to swap it anymore and we get a perfectly sorted array.</p><p>Code in ES5:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20075b30a70998a383cb364043376670/href">https://medium.com/media/20075b30a70998a383cb364043376670/href</a></iframe><p>And now let’s try rewriting this piece of code with the use of modern JavaScript!</p><h3>Variables (const, let)</h3><p>I’m going to cheat a little bit. Our current function is declared, but I’m going to rewrite it as a function expression and assign it to a constant variable called selectionSort. It will look something like this:</p><pre>const selectionSort = function (arr) {…}</pre><p>Now why would we want to use const instead of var ? The answer is simple, const prevents variable <strong>re-assignment. </strong>If you try to re-assign a value declared as const you’ll get an error. Don’t believe me?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*wWdekrSfehqEz7GL8uLoHg.png" /></figure><p>Also, although const is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Hoisting">hoisted</a>, it is not <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#sec-let-and-const-declarations">initialized</a>:</p><blockquote><strong>let</strong> and <strong>const</strong> declarations define variables that are scoped to the <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#running-execution-context">running execution context</a>&#39;s LexicalEnvironment. The variables are created when their containing <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#sec-lexical-environments">Lexical Environment</a> is instantiated but may not be accessed in any way until the variable&#39;s <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#prod-LexicalBinding">LexicalBinding</a> is evaluated.</blockquote><p>That means when you’re trying to access a variable before declaration using const or let you’ll get an error. Just try it out yourself, open the console and execute the following code:</p><pre>{<br>  console.log(hello);<br>  var hello;<br>}</pre><p>You probably didn’t get an error. Now execute the same piece of code, but swap var with const or let. If you’re using chrome you’ll see this lovely message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*XMD_oys4MOmqdx2GwgDKEg.png" /></figure><p>Another benefit of const and let is that they’re both block-scoped. That means when you declare them in a block they will only be valid for that block. Let’s try it out once again. Open your console and paste this piece of code:</p><pre>{ <br>  var notBlockScoped = ‘hello’<br>}</pre><p>If you try to access it after the block you’ll surely get the value back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*d5o8G4jHvXUW3myTLliAcQ.png" /></figure><p>Now again swap the var with let or const. What did we get?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*l8xQuWhNE_43oNasBJk2kw.png" /></figure><p>Ah, that’s right. It’s not defined. You can see how this helps preventing bugs, as the variables do not leak out to the outer context. What we’ll do is we’ll change all of our var to be let and const because of all the benefits that they offer. Use const when you don’t want variable re-assignment and let if you want to change the value later on.</p><p>Info on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a> if you’d like to know more.</p><h3>Arrow functions</h3><p>Let’s use an arrow function to compact our function expression just a tiny bit more. We’ll go from this:</p><pre>const selectionSort = function (arr) {…}</pre><p>To this:</p><pre>const selectionSort = arr =&gt; {...}</pre><p>You can probably tell that we lost the parenthesis along the way as well. They are optional when you declare only one parameter name:</p><pre>arr =&gt; {...} // this is fine<br>arr, number =&gt; {...} // this will not work<br>(arr, number) =&gt; {...} // but this will!</pre><p>You should be aware that the this keyword behaves differently when using arrow functions. It doesn’t have it’s own <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this">this</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_arguments">arguments</a> binding. You also can not use it as a constructor, which means this won’t work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*dGFA_6EgqiYZp2qkFnMyGw.png" /></figure><p>But this will:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*O129VXizxbGu1ri3lJCJXw.png" /></figure><p>If you don’t know much about arrow functions I really recommend <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">reading about them.</a></p><h3>forEach, for…of</h3><p>In the real world I wouldn’t rewrite our for loops in any way, they work just fine. But still, we can definitely do that. Let’s look at what we can do with our first loop.</p><h4>forEach</h4><p>Currently looks like this:</p><pre>for (let i = 0; i &lt; arr.length; i++) {…} </pre><p>Rewrite it to:</p><pre>arr.forEach((value, index) =&gt; {…})</pre><p>As you can probably tell forEach executes a function for each and every array item. In the first callback argument we get the array value and in the second we get the index. This isn’t really ideal in our scenario, because we’re not really that interested in the value itself, but more in the index. Let’s look at an example with for…of</p><p>More info on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">forEach</a>.</p><h4>for…of</h4><p>Again, our current first loop implementation looks like this:</p><pre>for (let i = 0; i &lt; arr.length; i++) {…}</pre><p>With for…of:</p><pre>for (let i of arr.keys()) {…}</pre><p>But why do we have arr.keys()? Well, because for…of iterates over so called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">iterable objects</a>. If you’re like me you don’t really know for sure what an iterable object is, but in reality the concept itself is not that difficult. Iterable objects are just JavaScript objects that define their iteration behavior with the for...of loop, basically what values are looped over. Some built-in types are Array, String, Map, etc.</p><p>When we iterate over an Array (and you can try it out yourself) we only get the array value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*O9m4OKX_6CvErLQHwgdQKw.png" /></figure><p>Unfortunately, that’s not what we’re interested in, we want to have the index of the array. For that we can use built-in method called keys(). <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys">The </a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys">keys() method returns a new </a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys">Array Iterator object that contains the keys for each index in the array.</a> Now we can loop through the array and get the piece that we’re interested in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*kX0jfrlKl9jJiOV_f4dTZQ.png" /></figure><p>Great! It’s really not the best use case, but the concept of the for...of loop is really powerful and you can do a lot of cool things with it.</p><p>More info on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for…of loop.</a></p><p><strong>Note:</strong> for…of loops cousin for…in is not included, because it’s built for iterating over object properties and is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Why_Use_for...in">not recommended in use with arrays</a>.</p><h3>Destructuring assignment</h3><p>Uhhh, that sounds really difficult. And you’re writing about it at the end of the article? When I’m already tired from all of the const and let and var and whatever... But bear with me, it’s not that difficult. It’s just syntactic sugar to unpack values from arrays, or properties from objects, into distinct values. Let’s take a look at a simple example for destructuring:</p><pre>const arr = [10, 20]<br>const [a, b] = arr</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*mAAUjIiWG03-BsuauZt2UA.png" /></figure><p>This is really cool. We can unpack our array values into distinct variables. With destructuring assignment we can do the following:</p><pre>const [a, b] = [30, 40]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*a1Bb54qUUtlDwWSlDQuShQ.png" /></figure><p>This comes in handy for swapping array values. In ES5 world you need to create a temp variable in order to not lose information on the array element that you’re swapping. Let’s take a closer look.</p><pre>const arr = [10, 20]<br>arr[0] = arr[1] // This doesn&#39;t work, now both of our values are 20<br>arr[1] = arr[0] // Will also become 20 :(</pre><p>For that you need to have a temp variable which saves the previous information and that’s what we’re doing in our <a href="https://gist.github.com/EdvinasDaugirdas/0e2dcd2023eac28e6b54ef67ecd988a3#file-selectionsort-js-L11">example</a>. But with the help of destructuring assignment we can refactor it to:</p><pre>[arr[i], arr[minimumIndex]] = [arr[minimumIndex], arr[i]]</pre><p>We’re just swapping the values around really elegantly. If this doesn’t makes sense try looking at our previous example again at the top when we assign const [a, b] = [30, 40]</p><h3>Summary</h3><p>With all of that being said our end result looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/629ff6da2b9545c1aa2e4e1a71c0a883/href">https://medium.com/media/629ff6da2b9545c1aa2e4e1a71c0a883/href</a></iframe><p>I hope that you’ve learnt some new concepts or syntax along the way.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13db14cbd52e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/learning-modern-javascript-through-selection-sort-13db14cbd52e">Learning modern JavaScript through Selection sort</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>