<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Danieo's Blog]]></title><description><![CDATA[WebDev, programming and my thoughts]]></description><link>https://blog.danieo.me/</link><image><url>https://blog.danieo.me/favicon.png</url><title>Danieo&apos;s Blog</title><link>https://blog.danieo.me/</link></image><generator>Ghost 4.12</generator><lastBuildDate>Thu, 15 Jan 2026 14:44:13 GMT</lastBuildDate><atom:link href="https://blog.danieo.me/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[JavaScript's asynchronicity - Promises, callbacks and async/await]]></title><description><![CDATA[<p>One of the core concepts of JavaScript is asynchronicity, which means doing many things simultaneously. It&apos;s a solution for avoiding your code being blocked by a time-intensive operation (like an HTTP request). In this article, you&apos;re going to learn the basic concept of asynchronicity and how</p>]]></description><link>https://blog.danieo.me/javascript-asynchronicity/</link><guid isPermaLink="false">611be491704a6528a55722e2</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Daniel Budziński]]></dc:creator><pubDate>Mon, 23 Aug 2021 18:33:12 GMT</pubDate><content:encoded><![CDATA[<p>One of the core concepts of JavaScript is asynchronicity, which means doing many things simultaneously. It&apos;s a solution for avoiding your code being blocked by a time-intensive operation (like an HTTP request). In this article, you&apos;re going to learn the basic concept of asynchronicity and how to use it in JavaScript.</p><hr><h2 id="but-before-we-start">But before we start...</h2><p>... we need to cover some computer theory. Programming is the process of telling your computer what it&apos;s supposed to do, we communicate with it using <strong>code</strong>. Every code is just a set of instructions for our machine that we want to execute. Every line of our code is executed by a so-called <strong>thread</strong>. A <strong>thread </strong>is executing only one instruction at a time. Let&apos;s analyze this pseudo-code:</p><pre><code>set x to 10
set y to 5
add x to y save result to r
display r</code></pre><p>When we execute this code, a <strong>thread</strong> is going to firstly set our variables <code>x</code> value to 10, <strong>THEN </strong>it will set <code>y</code> to 5, <strong>AFTER THAT</strong> it is going to add these two numbers together and save the result to our variable <code>r</code> and at the end it will display the value of <code>r</code>. The keywords are <strong>THEN </strong>and <strong>AFTER THAT</strong>, our thread can&apos;t simultaneously set <code>x</code> to 10 and <code>y</code> to 5, it has to wait with setting <code>y</code> until setting <code>x</code> is done. &#xA0;This is type of code is named <strong>synchronous code -</strong> every instruction is executed one after another. With such simple operations, we&apos;re not going to find any issues, but what when we want to execute something that is time-consuming? Like downloading an image? Well, there&apos;s the tricky part. </p><p>Such an operation is a <strong>blocking code</strong> because it stops our <strong>thread </strong>from performing anything else until the image is downloaded. We don&apos;t want our users to wait every time such instruction occurs. Imagine downloading a meme and when it&apos;s happening your computer can&apos;t do anything else - your music player stops, desktop freezes, etc. - using such computers would be a pain. As you probably noticed, such things are not happening, you can listen to music, watch a video on YouTube and code your breakthrough project all at the same time. That&apos;s because computer engineers found a solution to this problem.</p><p>Wise people once thought, if one thread can execute one operation at a time, couldn&apos;t 16 threads execute 16 operations in parallel? Yes, they can - and that&apos;s the reason why modern CPUs have many cores and every core has many threads. Programs using many threads are <strong>multi-threaded</strong>.</p><figure class="kg-card kg-image-card"><img src="https://blog.danieo.me/content/images/2021/08/Multi-Threaded-1-.jpg" class="kg-image" alt="A diagram showing how multi-threaded apps work." loading="lazy" width="903" height="423" srcset="https://blog.danieo.me/content/images/size/w600/2021/08/Multi-Threaded-1-.jpg 600w, https://blog.danieo.me/content/images/2021/08/Multi-Threaded-1-.jpg 903w" sizes="(min-width: 720px) 720px"></figure><p>The problem with JavaScript is that it&apos;s not <strong>multi-threaded, </strong>JavaScript is <strong>single-threaded</strong>, so it can&apos;t use many threads to do many operations at the same time. We&apos;re left with the same problem again - is there any other way to fix this? Yes! It&apos;s writing <strong>asynchronous code</strong>.</p><p>Let&apos;s assume that you want to fetch posts from your server every time your user scrolls your website. For this, we need to make an API call. API calls are just HTTP requests, which means that our browser making such call needs to establish a connection to our server, then our server processes the request, then sends it back, then our browser needs to process it... it&apos;s all time-consuming, and waiting for it to finish will block other interactions on our website, but it would only happen if our code was <strong>synchronous</strong>. Most time-consuming things like HTTP requests are mostly handled not by our <strong>main thread</strong>, but by lower-level APIs implemented in our browser. <strong>Asynchronous code </strong>uses this principle. We don&apos;t have to wait for our browser to finish the HTTP request, we can just inform the browser that we need to make an HTTP request, the browser will handle it and report to us with the result - in the meantime, other code can be executed on the <strong>main thread</strong>.</p><figure class="kg-card kg-image-card"><img src="https://blog.danieo.me/content/images/2021/08/Asynchronous.jpg" class="kg-image" alt="A diagram showing how asynchronous code works" loading="lazy" width="1023" height="423" srcset="https://blog.danieo.me/content/images/size/w600/2021/08/Asynchronous.jpg 600w, https://blog.danieo.me/content/images/size/w1000/2021/08/Asynchronous.jpg 1000w, https://blog.danieo.me/content/images/2021/08/Asynchronous.jpg 1023w" sizes="(min-width: 720px) 720px"></figure><p>You probably noticed that<strong> asynchronous code</strong> is similar to <strong>multi-thread</strong> code. Well, kind of. Both help us to solve the problem with <strong>blocking code</strong>, but <strong>asynchronous code</strong> in JavaScript is pseudo-parallel. For example, if we want to run two compute-intensive calculations in parallel we can&apos;t do it until the execution is handled by something else (like a lower-level API of our browser). For real parallelism in JavaScript, we can use <strong>WebWorkers</strong>, which run specified code in the background. However, <strong>WebWorkers </strong>are not today&apos;s topic, so I won&apos;t talk about them - for now. &#x1F609;</p><p>Ok, that&apos;s enough theory. How we can write this <strong>asynchronous code</strong> in JavaScript? There are two major ways to do it, the older method using <strong>callbacks</strong> and the newer method using <strong>Promises</strong>. It&apos;s time to look at them in deep.</p><h2 id="callbacks">Callbacks</h2><p>Earlier I said that when our asynchronous operation is done, we inform our <strong>main thread</strong> about it. The older way to report back is using a <strong>callback</strong>. A <strong>callback </strong>is basically a function that is called when our task is done. It can also carry arguments with data like a result of the asynchronous task. Let&apos;s analyze some examples.</p><p>We are going to fetch information about Charmander from <em><a href="https://pokeapi.co/">pokeapi.co</a> </em>using <code>XMLHttpRequest</code> API.</p><pre><code class="language-javascript">const xhr = new XMLHttpRequest();
xhr.open(&apos;GET&apos;, &apos;https://pokeapi.co/api/v2/pokemon/charmander&apos;, true);
xhr.responseType = &apos;json&apos;;
xhr.onload = (e) =&gt; {
  if (xhr.status === 200) {
    console.dir(xhr.response);
  } else {
    console.error(&apos;Something went wrong...&apos;);
  }
};
xhr.send(null);</code></pre><p>The first 3 lines are just configuring the <code>XMLHttpRequest</code> object. The thing that interests us the most is <code>xml.onload</code>, because here we specify our <strong>callback </strong>using an arrow function. When we send our request, the browser is going to handle it and when it&apos;s done it&apos;s going to call our <strong>callback </strong>function in which we can further process the received data.</p><p>Another common example of using callbacks to handle asynchronous tasks are <strong>Event Listeners</strong>. Look at the code below.</p><pre><code class="language-javascript">const button = document.getElementById(&apos;myButton&apos;);
button.addEventListener(&apos;click&apos;, (event) =&gt; {
  console.info(&apos;Button clicked!&apos;);
});</code></pre><p>We get our button element using its ID, then we attach a <strong>listener </strong>to its <code>click</code> event. Listener functions are nothing else than just <strong>callbacks</strong>. Our arrow function is called every time the user clicks this button. This whole process is not blocking code, because we don&apos;t have to wait for the click in our main thread. Events are handled by the browser and we only attach a callback that is <strong>called when the click is done</strong>.</p><p>One more example. <strong>Timeout </strong>and <strong>Intervals </strong>are also asynchronous.</p><pre><code class="language-javascript">const timeout = setTimeout(() =&gt; {
  console.info(&apos;Boo!&apos;);
}, 5000);</code></pre><p>The <strong>Timeout </strong>or <strong>Interval </strong>handler function is also a <strong>callback </strong>and it&apos;s called only after a certain time has been deducted. The whole time measurement code is handled by our browser&apos;s components, not by us, so we are only informed when the right amount of time has passed.</p><p>Now let&apos;s combine some of these examples as a recap.</p><pre><code class="language-javascript">const button = document.getElementById(&apos;myButton&apos;);
button.addEventListener(&apos;click&apos;, (event) =&gt; {
  console.info(&apos;Button clicked!&apos;);
});

const request = setTimeout(() =&gt; { // This timeout is going to simulate a very long HTTP request
  console.info(&apos;Response received!&apos;);
}, 5000);
</code></pre><p>In this code, we attach a listener to our button and make an HTTP request. If you run this example, you can see that you can click the button despite the fact that the HTTP request is being made. You don&apos;t have to wait with the request until the button is clicked, nor do you have to wait with handling the button click until the HTTP request is done - no operation is blocked. That&apos;s the power of asynchronicity!</p><h2 id="promises">Promises</h2><p>The modern way to handle asynchronicity in JavaScript is to use <strong>Promises</strong>. You can think of them like a promise made by people. It&apos;s not the result of something, it&apos;s just a promise that something will be done in the future (or not). If your roommate promises you to take out the trash this week, she&apos;s telling you that she will do it in the future, but not now. You can focus on your things and after some hours your roommate is going to tell you that the trashcan is empty and that she fulfilled her promise. Your roommate can also tell you, that she couldn&apos;t fulfill it because there is a raccoon living in your trashcan and it behaves aggressively when you try to take out the litter bag. In this case, she couldn&apos;t keep this promise, because she doesn&apos;t want to be attacked by an aggressive raccoon.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://blog.danieo.me/content/images/2021/08/vincent-dorig-Y60q9L_ZS00-unsplash.jpg" class="kg-image" alt="A photo of a raccoon" loading="lazy" width="2000" height="1333" srcset="https://blog.danieo.me/content/images/size/w600/2021/08/vincent-dorig-Y60q9L_ZS00-unsplash.jpg 600w, https://blog.danieo.me/content/images/size/w1000/2021/08/vincent-dorig-Y60q9L_ZS00-unsplash.jpg 1000w, https://blog.danieo.me/content/images/size/w1600/2021/08/vincent-dorig-Y60q9L_ZS00-unsplash.jpg 1600w, https://blog.danieo.me/content/images/size/w2400/2021/08/vincent-dorig-Y60q9L_ZS00-unsplash.jpg 2400w" sizes="(min-width: 720px) 720px"><figcaption>Remember, not every raccoon is aggressive! Photo by <a href="https://unsplash.com/@vincentdoerig?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Vincent D&#xF6;rig</a> on <a href="https://unsplash.com/s/photos/raccoon-trash?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A <strong>Promise </strong>can be in one of three states:</p><ul><li><em>pending </em>- This is an initial state, the <strong>Promise </strong>is running and we don&apos;t know if it&apos;s fulfilled or something went wrong.</li><li><em>fulfilled </em>(or<em> resolved</em>)<em> </em>- Everything is ok. The <strong>Promise </strong>has completed its task successfully.</li><li><em>rejected </em>- Something went wrong and the operation failed. </li></ul><p>So let&apos;s create our first <strong>promise</strong>.</p><pre><code class="language-javascript">const promise = new Promise((resolve) =&gt; {
  setTimeout(resolve, 3000);
});</code></pre><p>We are creating a new <strong>Promise</strong> object by calling the <strong>Promise </strong>constructor. As you can see in this example the constructor of a <strong>Promise </strong>object takes an arrow function as an argument. This argument is called an <strong>executor </strong>or <strong>executor function</strong>. The executor is going to be called when we are creating our <strong>Promise </strong>object and it is the connector between your <strong>Promise </strong>and the result. The executor takes two arguments a <strong>resolve function</strong> and a <strong>reject function </strong>- both of them are used to control your <strong>Promise</strong>. Resolve is used to mark our promise as fulfilled and return result data. Reject is used to notify that something is wrong and the <strong>Promise </strong>is not going to be fulfilled - it&apos;s <em>rejected</em>. Reject like resolve can also carry data, in most cases, it carries information about why the <strong>Promise </strong>was not fulfilled. </p><p>Resolving and rejecting promises can be handled by methods, provided by the <strong>Promise </strong>object. Take a look at this code.</p><pre><code class="language-javascript">const promise = new Promise((resolve) =&gt; {
  setTimeout(resolve, 3000);
});

promise.then(() =&gt; {
  console.info(&apos;3 seconds have passed!&apos;);
});</code></pre><p>Our promise is very simple, our executor is going to create a Timeout and call our resolve function after 3 seconds. We can intercept this information using <code>.then()</code> by providing a <strong>callback </strong>to it. <code>.then()</code> takes two arguments, the first is a callback called, when the Promise is <em>fulfilled</em>, the second one (not seen in this example) is a callback called when the Promise is <em>rejected</em>. But for handling rejected promises we can use a more convenient method - <code>.catch()</code>. Let&apos;s modify our example.</p><pre><code class="language-javascript">const promise = new Promise((resolve, reject) =&gt; {
  setTimeout(() =&gt; {
    const number = Math.floor(Math.random()*100);

    if (number % 2 === 0) {
      resolve(number);
    }

    reject(new Error(&apos;Generated number is not even!&apos;));
  }, 3000);
});

promise.then((result) =&gt; {
  console.info(&apos;Promise fulfilled!&apos;);
  console.info(`${result} is even.`);
}).catch((error) =&gt; {
  console.info(&apos;Promise rejected!&apos;);
  console.error(error);
});</code></pre><p>This code after 3 seconds is going to generate a random number and check if it&apos;s even or not. If it&apos;s even then the Promise is resolved and we return the even number, if not, we reject the Promise with an error message. <code>.catch()</code> as an argument accepts a callback that is called when the Promise is rejected. </p><p>We can also reject Promises by throwing an error.</p><pre><code class="language-javascript">const promise = new Promise((resolve) =&gt; {
  throw new Error(&apos;Error message&apos;);
});

promise.then((result) =&gt; {
  console.info(&apos;Promise fulfilled!&apos;);
}).catch((error) =&gt; {
  console.info(&apos;Promise rejected!&apos;);
  console.error(error);
});</code></pre><p>However, this has some limitations. If we throw an error inside an asynchronous function like Timeout&apos;s callback in our example, <code>.catch()</code> will not be called and the thrown error will behave as an <em>Uncaught Error</em>.</p><pre><code class="language-javascript">const promise = new Promise((resolve) =&gt; {
  setTimeout(() =&gt; {
    const number = Math.floor(Math.random()*100);

    if (number % 2 === 0) {
      resolve(number);
    }

    throw new Error(&apos;Generated number is not even!&apos;); // This is an Uncaught Error
  }, 3000);
});

promise.then((result) =&gt; {
  console.info(&apos;Promise fulfilled!&apos;);
  console.info(`${result} is even.`);
}).catch((error) =&gt; {
  console.info(&apos;Promise rejected!&apos;);
  console.error(error);
});</code></pre><p>Also, you need to remember that every error thrown after calling <code>resolve()</code> is going to be silenced.</p><pre><code class="language-javascript">const promise = new Promise((resolve) =&gt; {
  resolve();
  throw new Error(&apos;Error message&apos;); // This is silenced
});</code></pre><p>Beside <code>.then()</code> and <code>.catch()</code> we also have a third method - <code>.finally()</code>. Finally is called when the Promise is done, it doesn&apos;t bother if it was resolved or rejected, it runs after <code>.then()</code> and <code>.catch()</code>.</p><pre><code class="language-javascript">const promise = new Promise((resolve, reject) =&gt; {
  if (Math.random() &lt; 0.5) {
    resolve(&apos;Promise fulfilled&apos;);
  }

  reject(new Error(&apos;Promise rejected&apos;));
});

promise.then((result) =&gt; {
  console.dir(result); // Runs only when the Promise is resolved
}).catch((error) =&gt; {
  console.error(error); // Run only when the Promise is rejected
}).finally(() =&gt; {
  console.dir(&apos;Promise has finished its work&apos;); // Run everytime the Promise is finished
});</code></pre><p>Now, let&apos;s analyze a real-case example.</p><pre><code class="language-javascript">const fetchCharmanderData = fetch(&apos;https://pokeapi.co/api/v2/pokemon/charmander&apos;);

fetchCharmanderData.then((response) =&gt; {
  if (response.status === 200) {
    return response.json();
  } else {
    throw new Error(response.statusText);
  }
}).then((data) =&gt; {
  console.dir(data);
}).catch((error) =&gt; {
  console.error(error);
});</code></pre><p>This code will fetch information about Charmander from <em><a href="https://pokeapi.co/">pokeapi.co</a></em> but it uses the new, promise-based <strong>fetch API</strong>. Fetch will make an HTTP request and return a Promise for it. When the data is fetched, we process the response. If we received a HTTP status 200 (OK) we are returning the JSON representation of the response body, if the status code is different (like 404 not found or 500 internal server error) we throw an error with a status message. As you see, we are using <code>.then()</code> twice. The first time is used, as I mentioned, to process the response, the second time we use <code>.then()</code> to process a second <strong>Promise.</strong> <code>response.json()</code> also returns a Promise (JSON parsing can also take some time so it can also be blocking code, that&apos;s why we want to make it asynchronous). Basically, this proves to us that you can have a Promise that resolves another Promise and you can handle them one after another by chaining control methods like <code>then</code>, <code>catch</code> and <code>finally</code>.</p><h2 id="asyncawait">async/await</h2><p>Chaining <code>.then()</code>, <code>.catch()</code> and <code>.finally()</code> can be sometimes painful and lead to the creation of hard-to-read code. ES8 (or EcmaScript 2017) introduced some <em>syntax sugar</em> for easier handling promises - <strong>async </strong>and <strong>await</strong>. Let&apos;s rewrite our Charmander example using async/await.</p><pre><code class="language-javascript">(async () =&gt; {
  const response = await fetch(&apos;https://pokeapi.co/api/v2/pokemon/charmander&apos;);

  try {
    if (response.status === 200) {
      const charmanderData = await response.json();
      console.dir(charmanderData);
    } else {
      throw new Error(response.statusText);
    }
  } catch (error) {
    console.error(error);
  }
})();</code></pre><p>This code does exactly the same which is done by the previous code - it&apos;s only written in a different way. We can&apos;t use <strong>await </strong>outside of asynchronous functions, so we are bypassing it by creating a self-calling async function. Inside this function, we are waiting for the response returned by <code>fetch()</code>. After we receive the response we are going to check its status code, when it&apos;s OK we await for the response body to be parsed and after that, we are going to output it. You probably noticed the missing of <code>.catch()</code>. We replaced it with a try-catch block, basically, it is going to do the same thing as <code>.catch()</code>. If anything inside <code>try</code> throws an error the code will stop to execute and the error handling code inside <code>catch</code> will be run instead.</p><p>I mentioned <strong>async functions </strong>and that<strong> await </strong>can be used only inside them. It is a new type of functions introduced in ES8, and, simplifying, it&apos;s a function that utilizes Promise-based behavior, which means that an async function always returns a Promise. It can be then awaited in another async function or treated like a Promise.</p><pre><code class="language-javascript">async function getCharmanderData() {
  const response = await fetch(&apos;https://pokeapi.co/api/v2/pokemon/charmander&apos;);
  return response.json();
}

(async () =&gt; {
  console.dir(await getCharmanderData());
})();</code></pre><blockquote><strong>NOTE.</strong> This example was simplified, and no exception handling is now included.</blockquote><p>We moved our logic that is responsible for fetching Charmander&apos;s data from <em><a href="https://pokeapi.co/">pokeapi.co</a></em> to an async function. After this, every time, when we need that data we can simply call this function with <strong>await </strong>and we can deal with it without writing long promise chains.</p><p>I said that an async function can be treated like a Promise, and here is an example of how we can do this.</p><pre><code class="language-javascript">async function getCharmanderData() {
  const response = await fetch(&apos;https://pokeapi.co/api/v2/pokemon/charmander&apos;);
  return response.json();
}

getCharmanderData().then((data) =&gt; {
  console.dir(data);
});</code></pre><p>Await can also be used on normal functions that return a Promise.</p><pre><code class="language-javascript">function delay(time) {
  return new Promise((resolve) =&gt; {
    setTimeout(resolve, time);
  });
}

(async () =&gt; {
  console.info(&apos;Start!&apos;);
  await delay(5000);
  console.info(&apos;5 seconds have passed.&apos;);
})();</code></pre><h2 id="promise-helpers">Promise helpers</h2><p>The <strong>Promise </strong>object has also some pretty useful methods that can help us with handling many Promises.</p><h3 id="promiseall">Promise.all()</h3><p><code>Promise.all()</code> awaits for all passed Promises to be fulfilled and <em>resolves </em>all results to an array.</p><pre><code class="language-javascript">const charmander = fetch(&apos;https://pokeapi.co/api/v2/pokemon/charmander&apos;).then((response) =&gt; response.json());
const bulbasaur = fetch(&apos;https://pokeapi.co/api/v2/pokemon/bulbasaur&apos;).then((response) =&gt; response.json());
const squirtle = fetch(&apos;https://pokeapi.co/api/v2/pokemon/squirtle&apos;).then((response) =&gt; response.json());

Promise.all([charmander, bulbasaur, squirtle]).then((result) =&gt; {
  console.dir(result);
});</code></pre><p>Worth mentioning is the fact, that when one of the passed promises is <em>rejected</em> <code>Promise.all()</code> is also <em>rejected</em>.</p><h3 id="promiseallsettled">Promise.allSettled()</h3><p>It&apos;s similar to <code>Promise.all()</code> but it&apos;s not rejected when one (or more) of the passed promises is <em>rejected</em>.</p><pre><code class="language-javascript">const charmander = fetch(&apos;https://pokeapi.co/api/v2/pokemon/charmander&apos;).then((response) =&gt; response.json());
const fail = fetch(&apos;https://pokeapi.co/api/v2/pokemon/non-existing&apos;).then((response) =&gt; response.json()); // This Promise is going to fail
const squirtle = fetch(&apos;https://pokeapi.co/api/v2/pokemon/squirtle&apos;).then((response) =&gt; response.json());

Promise.allSettled([charmander, fail, squirtle]).then((result) =&gt; {
  console.dir(result);
});</code></pre><h3 id="promiseany">Promise.any()</h3><p><code>Promise.any()</code> is fulfilled when any of the passed Promises is fulfilled. It is also going to return the result of the first resolved <strong>Promise</strong>. When none of the passed promises is fulfilled <code>Promise.any()</code> is going to be <em>rejected</em>.</p><pre><code class="language-javascript">const charmander = fetch(&apos;https://pokeapi.co/api/v2/pokemon/charmander&apos;).then((response) =&gt; response.json());
const bulbasaur = fetch(&apos;https://pokeapi.co/api/v2/pokemon/bulbasaur&apos;).then((response) =&gt; response.json());
const squirtle = fetch(&apos;https://pokeapi.co/api/v2/pokemon/squirtle&apos;).then((response) =&gt; response.json());

Promise.any([charmander, bulbasaur, squirtle]).then((result) =&gt; {
  console.dir(result);
});</code></pre><h3 id="promiserace">Promise.race()</h3><p>It is resolved when any of the passed promises is <em>resolved </em>or <em>rejected</em>.</p><pre><code class="language-javascript">const charmander = fetch(&apos;https://pokeapi.co/api/v2/pokemon/charmander&apos;).then((response) =&gt; response.json());
const bulbasaur = fetch(&apos;https://pokeapi.co/api/v2/pokemon/bulbasaur&apos;).then((response) =&gt; response.json());
const squirtle = fetch(&apos;https://pokeapi.co/api/v2/pokemon/squirtle&apos;).then((response) =&gt; response.json());

Promise.race([bulbasaur, charmander, squirtle]).then((result) =&gt; {
  console.dir(result);
});</code></pre><hr><p>Now you should have a better understanding of JavaScript&apos;s asynchronicity. As homework try to play with <a href="https://pokeapi.co/">pokeapi.co</a> and the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">Fetch API</a>. Create custom Promises that are going to fetch Pokemons after a certain delay or Fetch data based on something you received in an earlier Promise. You can also use async/await and Promise helpers in your code to experiment even more with this topic. See you (or read you?) and happy coding!</p>]]></content:encoded></item><item><title><![CDATA[JavaScript array methods 2/3 - iterating arrays]]></title><description><![CDATA[<p>As we know, arrays are collections of elements. JavaScript arrays have something named iteration methods - these methods operate on every element of the collection and can help us with creating new arrays based on individual entries of our original array or just simply do something with every single element.</p>]]></description><link>https://blog.danieo.me/javascript-array-methods-2/</link><guid isPermaLink="false">6117b31e704a6528a5571fb7</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Tutorials]]></category><dc:creator><![CDATA[Daniel Budziński]]></dc:creator><pubDate>Tue, 17 Aug 2021 11:24:58 GMT</pubDate><content:encoded><![CDATA[<p>As we know, arrays are collections of elements. JavaScript arrays have something named iteration methods - these methods operate on every element of the collection and can help us with creating new arrays based on individual entries of our original array or just simply do something with every single element. In this part of our JavaScript array methods series, we are going to cover them in deep.</p><hr><h2 id="table-of-contents">Table of contents</h2><ul><li><a href="#looping-through-an-array">Looping through an array</a></li><li><a href="#modify-all-elements-of-an-arraymapping-arrays">Modify all elements of an array - mapping arrays</a></li><li><a href="#reducing-arrays">Reducing arrays</a></li><li><a href="#check-if-every-element-fulfils-your-condition">Check if every element fulfils your condition</a></li><li><a href="#check-if-any-element-fulfils-your-condition">Check if any element fulfils your condition</a></li><li><a href="#filtering-arrays">Filtering arrays</a></li></ul><h2 id="looping-through-an-array">Looping through an array</h2><p>Looping (or iterating) through an array in most languages is commonly done using a for-loop. JavaScript is not different.</p><pre><code class="language-javascript">const images = [
  &quot;https://image-cdn.com/my-image-1.jpeg&quot;,
  &quot;https://image-cdn.com/my-image-2.jpeg&quot;,
  &quot;https://image-cdn.com/my-image-3.jpeg&quot;,
];

for (let i = 0; i &lt; images.length; ++i) {
  console.dir(images[i]);
}</code></pre><p>This code is going to output every single URL in the images array. As you see, our iteration is working, nothing special. It may look familiar to you if you worked with languages other than JavaScript.</p><p>However, it&apos;s not the only way to loop through our array. The Array prototype has implemented a <code>forEach</code> method, which calls a callback on every element of an array.</p><pre><code class="language-javascript">const images = [
  &quot;https://image-cdn.com/my-image-1.jpeg&quot;,
  &quot;https://image-cdn.com/my-image-2.jpeg&quot;,
  &quot;https://image-cdn.com/my-image-3.jpeg&quot;,
];

images.forEach((image) =&gt; console.dir(image));</code></pre><blockquote><strong>NOTE</strong>. You can access the index of the current element by passing a second argument to the function inside <code>forEach</code>.</blockquote><p>The result is the same - we&apos;ve printed every element of this array. Although there is a difference between a classic for loop and a <code>forEach</code> - performance<strong>. </strong><code>forEach</code> may be more convenient, but it&apos;s slower, so when you&apos;re dealing with big arrays you shouldn&apos;t use it.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://blog.danieo.me/content/images/2021/08/photo_2021-08-15_16-15-22.jpg" class="kg-image" alt="Benchmark results - for with an iterator is more performant than forEach" loading="lazy" width="899" height="335" srcset="https://blog.danieo.me/content/images/size/w600/2021/08/photo_2021-08-15_16-15-22.jpg 600w, https://blog.danieo.me/content/images/2021/08/photo_2021-08-15_16-15-22.jpg 899w" sizes="(min-width: 720px) 720px"><figcaption>Looping through a 10 000 elements array using three different methods.</figcaption></figure><p>In these benchmark results, you can see that there is a third method of iteration, which is a bit faster than <code>forEach</code> and more friendly than a classic <code>for</code> loop - I&apos;m talking about <code>for...of</code>. It was introduced after <code>for</code> and <code>forEach</code> and works...</p><pre><code class="language-javascript">const images = [
  &quot;https://image-cdn.com/my-image-1.jpeg&quot;,
  &quot;https://image-cdn.com/my-image-2.jpeg&quot;,
  &quot;https://image-cdn.com/my-image-3.jpeg&quot;,
];

for (const image of images) {
  console.dir(image);
}</code></pre><p>...the same way - I mean, it produces the same result. Being slightly more performant than <code>forEach</code> it&apos;s a better choice in most cases. Furthermore, opposite to <code>forEach</code>, it can be controlled with statements like <code>break</code><strong>, </strong>but this article is not about loops, so we&apos;re going to stop talking about <code>for...of</code>.</p><h2 id="modify-all-elements-of-an-arraymapping-arrays">Modify all elements of an array - mapping arrays</h2><p>Sometimes you&apos;ll need to transform every single element of your array and create a new array with these elements. In this case, <code>map</code> is the remedy. It simply runs a callback on every element and then creates a new array from the results.</p><pre><code class="language-javascript">const names = [&quot;dave&quot;, &quot;emma&quot;, &quot;alan&quot;, &quot;simon&quot;, &quot;stacy&quot;];
const capitalizedNames = names.map((name) =&gt; {
  return name[0].toUpperCase() + name.slice(1);
});

console.dir(capitalizedNames); // Output: [&quot;Dave&quot;, &quot;Emma&quot;, &quot;Alan&quot;, &quot;Simon&quot;, &quot;Stacy&quot;]</code></pre><p>This example is going to capitalize the first letter of every word in the array and return a new array consisting of capitalized words.</p><blockquote><strong>NOTE</strong>. You can access the index of the current element by passing a second argument to the function inside <code>map</code>.</blockquote><p>With using <code>map</code> comes one thing that you need to remember - the resulting array is the same length as the original array and every missing element is just changed to <em><code>undefined</code></em>. It can occur in a case like this:</p><pre><code class="language-javascript">const array = [&quot;1&quot;, &quot;6&quot;, &quot;17&quot;, &quot;boo!&quot;, &quot;32&quot;];

const numbers = array.map((x) =&gt; {
  const n = +x; // It&apos;s just a short way to cast a string into number
  if (!isNaN(n)) {
    return n;
  }
});

console.dir(numbers); // Output: [1, 6, 17, undefined, 32]</code></pre><p>In this example, we are converting an array of numeric strings to an array of numbers. There is only one problem, when conversion fails we get a NaN, and our statements under the condition are never called so this iteration never returns a value, in this case, <code>map</code> is going to return an <em>undefined </em>for that element.</p><h3 id="mapping-and-flattening">Mapping and flattening?</h3><p>Now, as we already covered <code>map</code>, let&apos;s talk about <code>flatMap</code><strong>, </strong>which works like<strong> </strong><code>map</code><strong> </strong>followed by<strong> </strong><code>flat</code>. Let&apos;s assume we have a text as an array of sentences and we want to tokenize it.</p><pre><code class="language-javascript">const text = [
  &quot;I&apos;ve gotta go. You&apos;ll find out in thirty years.&quot;,
  &quot;That&apos;s a great idea. I&apos;d love to park.&quot;,
  &quot;What the hell is a gigawatt? Lorraine, are you up there?&quot;,
];

const sentenceToken = text.map((sentence) =&gt; sentence.split(&quot; &quot;)).flat();
console.dir(sentenceToken); // Output: [ &quot;I&apos;ve&quot;, &quot;gotta&quot;, &quot;go.&quot;, &quot;You&apos;ll&quot;, &quot;find&quot;, &quot;out&quot;, &quot;in&quot;, &quot;thirty&quot;, &quot;years.&quot;, &quot;That&apos;s&quot;, &#x2026; ]</code></pre><blockquote><strong>NOTE</strong>. It&apos;s not a proper way to tokenize strings. It&apos;s a very simplified example to show how <code>flatMap</code> works.</blockquote><p>We map our text array and create an array of arrays containing single word tokens, then we flatten that array to get a one-dimensional array with all tokens. Simple, right? But do you know that we can do it better using <code>flatMap</code>?</p><pre><code class="language-javascript">const text = [
  &quot;I&apos;ve gotta go. You&apos;ll find out in thirty years.&quot;,
  &quot;That&apos;s a great idea. I&apos;d love to park.&quot;,
  &quot;What the hell is a gigawatt? Lorraine, are you up there?&quot;,
];

const sentenceToken = text.flatMap((sentence) =&gt; sentence.split(&quot; &quot;));
console.dir(sentenceToken); // Output: [ &quot;I&apos;ve&quot;, &quot;gotta&quot;, &quot;go.&quot;, &quot;You&apos;ll&quot;, &quot;find&quot;, &quot;out&quot;, &quot;in&quot;, &quot;thirty&quot;, &quot;years.&quot;, &quot;That&apos;s&quot;, &#x2026; ]</code></pre><p>It produces the same result, is a bit shorter, and is also slightly more performant.</p><figure class="kg-card kg-image-card"><img src="https://blog.danieo.me/content/images/2021/08/Screenshot-2021-08-15-at-19-44-06-JSBEN-CH-Benchmarking-for-JavaScript--.png" class="kg-image" alt="Benchmark result - flatMap is more performant than map + flat" loading="lazy" width="899" height="249" srcset="https://blog.danieo.me/content/images/size/w600/2021/08/Screenshot-2021-08-15-at-19-44-06-JSBEN-CH-Benchmarking-for-JavaScript--.png 600w, https://blog.danieo.me/content/images/2021/08/Screenshot-2021-08-15-at-19-44-06-JSBEN-CH-Benchmarking-for-JavaScript--.png 899w" sizes="(min-width: 720px) 720px"></figure><p>The choice should be obvious.</p><h2 id="reducing-arrays">Reducing arrays</h2><p>Reducing is a process where an array is reduced to a single value, it is achieved by calling a <strong>reducer function</strong> on every element. A reducer function can take four arguments:</p><ul><li><strong>Accumulator </strong>- it contains a value that is passed to every iteration, and after the final iteration, it becomes the value returned by <code>reduce</code>.</li><li><strong>Current value</strong> - as the name says, it&apos;s the value of the current element.</li><li><strong>Current index</strong> - an array index of the current iteration.</li><li><strong>Source array</strong> - the array on which <code>reduce</code> is called.</li></ul><p>Now some of you may wonder &quot;ok, but where can I use this method?&quot;. Let&apos;s assume we have an array of numbers and we want to count the sum of its elements. It can be done using a for and adding every element of this array to a variable, but also it can be done using <strong>reduce</strong>.</p><h3 id="counting-sum-of-array-elements">Counting sum of array elements</h3><pre><code class="language-javascript">const numbers = [77, 94, 668, 371, 2, 194, 54, 674, 7, 213, 26];
const sum = numbers.reduce((acc, value) =&gt; acc + value);
console.dir(sum); // Output: 2380</code></pre><p><strong>Reduce</strong> can also be used to find the minimal and maximal value in an array.</p><h3 id="finding-minimum-and-maximum-in-an-array">Finding minimum and maximum in an array</h3><pre><code class="language-javascript">const numbers = [77, 94, 668, 371, 2, 194, 54, 674, 7, 213, 26];
const min = numbers.reduce((acc, value) =&gt; acc &lt; value ? acc : value);
console.dir(min); // Output: 2</code></pre><pre><code class="language-javascript">const numbers = [77, 94, 668, 371, 2, 194, 54, 674, 7, 213, 26];
const max = numbers.reduce((acc, value) =&gt; acc &gt; value ? acc : value);
console.dir(max); // Output: 674</code></pre><p>But hey! JavaScript has methods like <code>min</code> and <code>max</code> in its <code>Math</code> object, can&apos;t we just use them? Of course, we can! Although, surprisingly, using reduce is <em>faster</em>. On a 10 000 elements array the result is as follows:</p><figure class="kg-card kg-image-card"><img src="https://blog.danieo.me/content/images/2021/08/Screenshot-2021-08-17-at-11-01-21-JSBEN-CH-Benchmarking-for-JavaScript--.png" class="kg-image" alt="Benchmark results - Finding arrays minimal value using reduce is faster than Math.min" loading="lazy" width="899" height="249" srcset="https://blog.danieo.me/content/images/size/w600/2021/08/Screenshot-2021-08-17-at-11-01-21-JSBEN-CH-Benchmarking-for-JavaScript--.png 600w, https://blog.danieo.me/content/images/2021/08/Screenshot-2021-08-17-at-11-01-21-JSBEN-CH-Benchmarking-for-JavaScript--.png 899w" sizes="(min-width: 720px) 720px"></figure><p>Let&apos;s check it also on a smaller array (with 10 elements).</p><figure class="kg-card kg-image-card"><img src="https://blog.danieo.me/content/images/2021/08/Screenshot-2021-08-17-at-11-04-25-JSBEN-CH-Benchmarking-for-JavaScript--.png" class="kg-image" alt="Benchmark results - Finding arrays minimal value using reduce is faster than Math.min" loading="lazy" width="899" height="249" srcset="https://blog.danieo.me/content/images/size/w600/2021/08/Screenshot-2021-08-17-at-11-04-25-JSBEN-CH-Benchmarking-for-JavaScript--.png 600w, https://blog.danieo.me/content/images/2021/08/Screenshot-2021-08-17-at-11-04-25-JSBEN-CH-Benchmarking-for-JavaScript--.png 899w" sizes="(min-width: 720px) 720px"></figure><h3 id="grouping-objects-in-an-array">Grouping objects in an array</h3><p>Another very useful case for <code>reduce</code> is grouping objects in an array by their properties. Let&apos;s take a look at this example:</p><pre><code class="language-javascript">const animals = [
  { name: &quot;Dog&quot;, group: &quot;mammals&quot; },
  { name: &quot;Eagle&quot;, group: &quot;birds&quot; },
  { name: &quot;Tiger&quot;, group: &quot;mammals&quot; },
  { name: &quot;Dolphin&quot;, group: &quot;mammals&quot; },
  { name: &quot;Frog&quot;, group: &quot;amphibians&quot; },
  { name: &quot;Parrot&quot;, group: &quot;birds&quot; },
];

const groupsSchema = {
  mammals: [],
  birds: [],
  amphibians: [],
};

const groups = animals.reduce((acc, value) =&gt; {
  acc[value.group].push(value);
  return acc;
}, groupsSchema);

console.dir(groups);</code></pre><p>In this example we got an array of animals, every animal has its name and the group it belongs to. Using <code>reduce</code> we group them into separate arrays based on the value of <code>group</code>. If you haven&apos;t noticed - we can pass an initial value for our <strong>accumulator </strong>by passing a second argument to <code>reduce</code>.</p><h3 id="reducing-backward">Reducing backward?</h3><p><code>reduce</code> is going to iterate from the lowest index to the highest (from start to end). However, sometimes we may need to reduce an array backward - in that case, we can use <code>reduceRight</code>. It works identically to reduce, only the iteration starts from the highest index and goes to the lowest index.</p><pre><code class="language-javascript">const array = [[1, 2], [3, 4], [5, 6]];
const result1 = array.reduce((acc, value) =&gt; acc.concat(value));
const result2 = array.reduceRight((acc, value) =&gt; acc.concat(value));
console.dir(result1); // Output: [1, 2, 3, 4, 5, 6]
console.dir(result2); // Output: [5, 6, 3, 4, 1, 2]</code></pre><h2 id="check-if-every-element-fulfils-your-condition">Check if every element fulfils your condition</h2><p>To check if all of the elements of an arrays are meeting our condition we can use <code>every</code>. This method runs a test on every element. If everything will pass, then it returns <code>true</code> - if not it returns <code>false</code>.</p><pre><code class="language-javascript">const positives = [1, 56, 17, 592, -5, 9];
const isEveryPositive = positives.every((value) =&gt; value &gt; 0);
console.dir(isEveryPositive); // Output: false</code></pre><pre><code class="language-javascript">const positives = [1, 56, 17, 592, 5, 9];
const isEveryPositive = positives.every((value) =&gt; value &gt; 0);
console.dir(isEveryPositive); // Output: true</code></pre><blockquote><strong>NOTE.</strong> The test function also accepts a second argument after <code>value</code>, it&apos;s the <code>index</code> of the current element.</blockquote><h2 id="check-if-any-element-fulfils-your-condition">Check if any element fulfils your condition</h2><p>When you want to check if one or more element pass your test, you can use <code>some</code>. It&apos;s similar to <code>every</code>, but it expects only <strong>some </strong>values to pass the test.</p><pre><code class="language-javascript">const positives = [&quot;Hammer&quot;, &quot;Screwdriver&quot;, null, &quot;Wrench&quot;];
const isSomeNull = positives.some((value) =&gt; value === null);
console.dir(isSomeNull); // Output: true</code></pre><pre><code class="language-javascript">const positives = [&quot;Hammer&quot;, &quot;Screwdriver&quot;, &quot;Pliers&quot;, &quot;Wrench&quot;];
const isSomeNull = positives.some((value) =&gt; value === null);
console.dir(isSomeNull); // Output: false</code></pre><blockquote><strong>NOTE.</strong> Similar to <code>every</code> you can also access the <code>index</code> of the current element by passing a second argument to the test function.</blockquote><h2 id="filtering-arrays">Filtering arrays</h2><p>Removing elements that don&apos;t fulfill our conditions can be pretty handy. <code>filter</code> creates a new array consisting of elements that pass our test.</p><pre><code class="language-javascript">const numbers = [456, 1837, 123, 416, 12, 312, 7];
const filtered = numbers.filter((value) =&gt; value &gt;= 100);
console.dir(filtered); // Output: [456, 1837, 123, 416, 312]</code></pre><h3 id="removing-duplicates-from-an-array">Removing duplicates from an array</h3><pre><code class="language-javascript">const pets = [&quot;Dog&quot;, &quot;Cat&quot;, &quot;Hamster&quot;, &quot;Dog&quot;, &quot;Canary&quot;];
const filtered = pets.filter((value, index, array) =&gt; array.indexOf(value) === index);
console.dir(filtered); // Output: [&quot;Dog&quot;, &quot;Cat&quot;, &quot;Hamster&quot;, &quot;Canary&quot;]</code></pre><blockquote><strong>NOTE</strong>. this method is not performant on big arrays. With bigger arrays consider using the ES6 way to create unique arrays.</blockquote><pre><code class="language-javascript">const pets = [&quot;Dog&quot;, &quot;Cat&quot;, &quot;Hamster&quot;, &quot;Dog&quot;, &quot;Canary&quot;];
const filtered = [...new Set(pets)];
console.dir(filtered); // Output: [&quot;Dog&quot;, &quot;Cat&quot;, &quot;Hamster&quot;, &quot;Canary&quot;]</code></pre><p>This will create a <code>Set</code> from our array and then convert it back to a classic array. Sets are collections like array but they have a unique constraint - they don&apos;t accept duplicates and every value is unique. Below is a test comparing these methods on a 1000 elements array.</p><figure class="kg-card kg-image-card"><img src="https://blog.danieo.me/content/images/2021/08/Screenshot-2021-08-17-at-13-12-12-JSBEN-CH-Benchmarking-for-JavaScript--.png" class="kg-image" alt="Benchmark result - creating a set of a big array is more performant than filtering duplicates" loading="lazy" width="899" height="249" srcset="https://blog.danieo.me/content/images/size/w600/2021/08/Screenshot-2021-08-17-at-13-12-12-JSBEN-CH-Benchmarking-for-JavaScript--.png 600w, https://blog.danieo.me/content/images/2021/08/Screenshot-2021-08-17-at-13-12-12-JSBEN-CH-Benchmarking-for-JavaScript--.png 899w" sizes="(min-width: 720px) 720px"></figure><p>and on a small 20 elements array.</p><figure class="kg-card kg-image-card"><img src="https://blog.danieo.me/content/images/2021/08/Screenshot-2021-08-17-at-13-12-58-JSBEN-CH-Benchmarking-for-JavaScript--.png" class="kg-image" alt="Benchmark result - filter is more performant on small arrays than creating a Set" loading="lazy" width="899" height="249" srcset="https://blog.danieo.me/content/images/size/w600/2021/08/Screenshot-2021-08-17-at-13-12-58-JSBEN-CH-Benchmarking-for-JavaScript--.png 600w, https://blog.danieo.me/content/images/2021/08/Screenshot-2021-08-17-at-13-12-58-JSBEN-CH-Benchmarking-for-JavaScript--.png 899w" sizes="(min-width: 720px) 720px"></figure><hr><p>And that&apos;s all! We are almost at the end of this short series! The last part is going to cover searching in arrays. For now, take care! If you like my work consider signing up for my newsletter.</p><h2 id="rest-of-the-series">Rest of the series</h2><ul><li><a href="https://blog.danieo.me/javascript-array-methods-1/">JavaScript array methods 1/3 - altering array</a></li></ul>]]></content:encoded></item><item><title><![CDATA[JavaScript array methods 1/3 - altering arrays]]></title><description><![CDATA[The Array prototype in modern JavaScript contains many useful methods which every developer should know. However, some of them were introduced...]]></description><link>https://blog.danieo.me/javascript-array-methods-1/</link><guid isPermaLink="false">610c0f57704a6528a5571994</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Tutorials]]></category><dc:creator><![CDATA[Daniel Budziński]]></dc:creator><pubDate>Thu, 12 Aug 2021 22:45:10 GMT</pubDate><content:encoded><![CDATA[<p>The Array prototype in modern JavaScript contains many useful methods which every developer should know. However, some of them were introduced in the more recent ECMAScript. So if you don&apos;t keep up with the newest standards or you&apos;re just a beginner - it is a good time to learn something new. I&apos;m also going to show you some tricks and trivia about these methods.</p><hr><h2 id="table-of-contents">Table of contents</h2><ul><li><a href="#how-to-add-new-items-to-an-array">How to add new items to an array?</a></li><li><a href="#how-to-concatmerge-arrays">How to concat/merge arrays?</a></li><li><a href="#removing-elements-from-the-array">Removing elements from the array</a></li><li><a href="#creating-a-string-from-an-arrayjoining-all-elements-into-one-string">Creating a string from an array - joining all elements into one string</a></li><li><a href="#creating-an-array-from-a-stringsplitting-strings">Creating an array from a string - splitting strings</a></li><li><a href="#how-to-reverse-an-array">How to reverse an array?</a></li><li><a href="#how-to-add-new-elements-to-the-beginning-of-an-array">How to add new elements to the beginning of an array?</a></li><li><a href="#how-to-sort-an-array-in-javascript">How to sort an array in JavaScript?</a></li><li><a href="#how-to-get-firstlastany-n-elements-from-an-array">How to get first/last/any n elements from an array?</a></li><li><a href="#how-to-flatten-arrays">How to flatten arrays?</a></li><li><a href="#how-to-copy-elements-within-an-array">How to copy elements within an array?</a></li></ul><h3 id="before-you-read">Before you read</h3><p>If you&apos;re an absolute beginner before reading this article you can check my <a href="https://blog.danieo.me/a-brief-introduction-to-javascript-arrays/">brief introduction to JavaScript arrays</a> where I discussed this construct in short.</p><hr><h2 id="how-to-add-new-items-to-an-array">How to add new items to an array?</h2><p><strong>push()</strong>! One of the most common operations that we can do on arrays. It simply adds new elements to the array.</p><pre><code class="language-javascript">const array = [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;];
array.push(&quot;&#x1F413;&quot;);
console.dir(array) // Output: [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F413;&quot;]</code></pre><p><strong>push()</strong> will automatically extend the size of the array and add our new element at the end. We can <strong>push()</strong> more than one element at once:</p><pre><code class="language-javascript">const array = [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;];
array.push(&quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F404;&quot;);
console.dir(array) // Output: [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F404;&quot;]</code></pre><p>It&apos;s also worth noting that <strong>push()</strong> returns the new <strong>length </strong>of the array.</p><pre><code class="language-javascript">const array = [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;];
console.dir(array.push(&quot;&#x1F409;&quot;)); // Output: 4
console.dir(array); // Output: [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;]</code></pre><p>Sometimes we may need to manually extend an array and add elements at certain indexes.</p><pre><code class="language-javascript">const array = [];
array[2] = &quot;&#x1F42C;&quot;;
console.dir(array); // Output: [undefined, undefined, &quot;&#x1F42C;&quot;]
array[0] = &quot;&#x1F405;&quot;;
array[1] = &quot;&#x1F409;&quot;;
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F42C;&quot;]</code></pre><p>In this example, we create an empty array. The next line extends its size to n+1 and adds <em>&#x1F42C; </em>as the last value.</p><blockquote>Thanks to the <strong>console.dir()</strong> in the third line you can see that there are some <em>undefined </em>values in this array. As I said in <a href="https://blog.danieo.me/a-brief-introduction-to-javascript-arrays">my brief introduction to JavaScript arrays</a>, when you&apos;re extending the length of an array, JavaScript creates new elements with <em>undefined </em>values to meet the new size.</blockquote><p>This method also works on existing arrays:</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;];
array[4] = &quot;&#x1F404;&quot;;
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, undefined, undefined, &quot;&#x1F404;&quot;]</code></pre><h2 id="how-to-concatmerge-arrays">How to concat/merge arrays?</h2><p>One of the possibilities is to use <strong>concat()</strong>:</p><pre><code class="language-javascript">const array1 = [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;];
const array2 = [&quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
const result = array1.concat(array2);
console.dir(result); // Output: [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;]</code></pre><p>It merges two or more arrays and returns the new array. Here&apos;s an example on three arrays:</p><pre><code class="language-javascript">const array1 = [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;];
const array2 = [&quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
const array3 = [&quot;&#x1F40E;&quot;, &quot;&#x1F404;&quot;];
const result  = array1.concat(array2, array3);
console.dir(result); // Output: [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F40E;&quot;, &quot;&#x1F404;&quot;]</code></pre><p>But what if I want to merge one array INTO another array without the need to assign a third variable? ES2015 introduced a so-called <em>destructuring assignment</em> which in combination with <strong>push()</strong> can do it!</p><pre><code class="language-javascript">const array1 = [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;];
const array2 = [&quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
array1.push(...array2);
console.dir(array1); // Output: [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;]</code></pre><p>Ta dam! Now we have all of the elements of the second array in our first array.</p><p>Using destructuring we can achieve a similar behavior to <strong>concat()</strong>. We just need to destruct the merged arrays into another array.</p><pre><code class="language-javascript">const array1 = [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;];
const array2 = [&quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
const array3 = [&quot;&#x1F40E;&quot;, &quot;&#x1F404;&quot;];
const result = [...array1, ...array2, ...array3];
console.dir(result);</code></pre><h2 id="removing-elements-from-the-array">Removing elements from the array</h2><h3 id="how-to-remove-the-last-element-from-the-array">How to remove the last element from the array?</h3><p>It&apos;s as simple as calling the <strong>pop() </strong>function on the array.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
array.pop();
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;]</code></pre><p><strong>pop()</strong> has also a useful property because it returns the removed element!</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
const lastElement = array.pop();
console.dir(lastElement); // Output: &quot;&#x1F404;&quot;</code></pre><h3 id="how-to-remove-the-first-element-from-the-array">How to remove the first element from the array?</h3><p>Here in handy comes <strong>shift()</strong>. Similar to <strong>pop()</strong> it also returns the element being removed.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
const firstElement = array.shift();
console.dir(firstElement); // Output: &quot;&#x1F405;&quot;
console.dir(array); // Output: [&quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;]</code></pre><h3 id="how-to-remove-elements-from-the-array-on-a-specific-index">How to remove elements from the array on a specific index?</h3><p>To remove a specific element we can use the <strong>delete </strong>operator.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
delete array[1];
console.dir(array); // Output: [&quot;&#x1F405;&quot;, undefined, &quot;&#x1F404;&quot;]</code></pre><p>It removes the element completely - the array now does not have an element with index 1. The interesting part of this is the fact, that we are still left with an array with a length of 3. If you want to leave the element and don&apos;t want it to have value just set it to <em>undefined</em>. Example:</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
delete array[1];
console.dir(array.length); // Output: 3
console.dir(1 in array); // Output: false
console.dir(array); // Output: [&quot;&#x1F405;&quot;, undefined, &quot;&#x1F404;&quot;]

array[1] = &apos;&#x1F42C;&apos;;
array[1] = undefined;
console.dir(array.length); // Output: 3
console.dir(1 in array); // Output: true
console.dir(array); // Output: [&quot;&#x1F405;&quot;, undefined, &quot;&#x1F404;&quot;]</code></pre><p>But what when we want to remove the element AND shorten the array? For this case, we can use <strong>splice()</strong>.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
array.splice(1, 1);
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F404;&quot;]</code></pre><p>The first argument of <strong>splice()</strong> is the <em>startIndex</em>, it sets the place where we want to start &quot;cutting&quot; our array. The second argument determines the length of the &quot;cut&quot;. In 0ut case we only want to delete &quot;&#x1F42C;&quot; so we just start &quot;cutting&quot; on index 1 and we want to remove just one element. Here is another example of removing more elements.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
array.splice(2, 3);
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F409;&quot;]</code></pre><p>Now our &quot;cut&quot; has started on &quot;&#x1F404;&quot; and we wanted to remove three elements starting from that place.</p><p>With splice, we can also fill the gap of the removed elements by passing more arguments.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
array.splice(2, 2, &quot;&#x1F416;&quot;, &quot;&#x1F999;&quot;);
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F416;&quot;, &quot;&#x1F999;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;]</code></pre><p>or using destructuring, we can fill the gap with another array.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
const fillArray = [&quot;&#x1F416;&quot;, &quot;&#x1F999;&quot;];
array.splice(2, 2, ...fillArray);
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F416;&quot;, &quot;&#x1F999;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;]</code></pre><p>Now let&apos;s compare all three methods and see the results!</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
delete array[1];
console.dir(array.length); // Output: 3
console.dir(1 in array); // Output: false
console.dir(array); // Output: [&quot;&#x1F405;&quot;, undefined, &quot;&#x1F404;&quot;]

array[1] = &quot;&#x1F42C;&quot;;
array[1] = undefined;
console.dir(array.length); // Output: 3
console.dir(1 in array); // Output: true
console.dir(array); // Output: [&quot;&#x1F405;&quot;, undefined, &quot;&#x1F404;&quot;]

array[1] = &quot;&#x1F42C;&quot;;
array.splice(1,1);
console.dir(array.length); // Output: 2
console.dir(1 in array); // Output: true
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F404;&quot;]</code></pre><p>Reassuming: </p><ul><li><strong>delete </strong>removes the element but does not affect the array&apos;s size.</li><li>setting an element to <em>undefined </em>does not remove it completely nor affects the array&apos;s size.</li><li><strong>splice()</strong> removes the element and affects the array&apos;s size.</li></ul><h2 id="creating-a-string-from-an-arrayjoining-all-elements-into-one-string">Creating a string from an array - joining all elements into one string</h2><p>Sometimes we need to create one string from all of the elements of the array, we can do it by using <strong>join()</strong>.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
const result = array.join();
console.dir(result); // Output: &quot;&#x1F405;,&#x1F42C;,&#x1F404;,&#x1F412;,&#x1F413;,&#x1F409;&quot;</code></pre><p>We can also specify the separator by passing it as the first argument.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
const result = array.join(&apos; | &apos;);
console.dir(result); // Output: &quot;&#x1F405; | &#x1F42C; | &#x1F404; | &#x1F412; | &#x1F413; | &#x1F409;&quot;</code></pre><h2 id="creating-an-array-from-a-stringsplitting-strings">Creating an array from a string - splitting strings</h2><p>We can achieve this by calling <strong>split()</strong> on our string. I know that <strong>split()</strong> is not a part of the Array prototype, but I thought that I should mention it when I&apos;m talking about its counterpart - <strong>join()</strong>.</p><pre><code class="language-javascript">const string = &quot;&#x1F405;,&#x1F42C;,&#x1F404;,&#x1F412;,&#x1F413;,&#x1F409;&quot;;
const result = string.split();
console.dir(result); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;]</code></pre><p>The default separator for <strong>split()</strong> is &quot;,&quot; but we can change it to whatever we want.</p><pre><code class="language-javascript">const string = &quot;&#x1F405;|&#x1F42C;|&#x1F404;|&#x1F412;|&#x1F413;|&#x1F409;&quot;;
const result = string.split(&quot;|&quot;);
console.dir(result); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;]</code></pre><h2 id="how-to-reverse-an-array">How to reverse an array?</h2><p>JavaScript also has a method for this - and (how surprising...) it&apos;s named... <strong>reverse()</strong>.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
const result = array.reverse();
console.dir(result); // Output: [&quot;&#x1F404;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;]</code></pre><p>But there is one problem with this method. It&apos;s mutating our original array. Well, it is only a problem if you want to preserve the original array.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
const result = array.reverse();
console.dir(result); // Output: [&quot;&#x1F404;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;]
console.dir(array); // Output: [&quot;&#x1F404;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;]</code></pre><p>What can we do to solve this <em>issue</em>? Well... just call <strong>concat()</strong> or <strong>slice()</strong> without any arguments.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
const result = array.concat().reverse();
console.dir(result); // Output: [&quot;&#x1F404;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;]
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;]</code></pre><blockquote><strong>NOTE.</strong> This works because <strong>concat()</strong> and <strong>slice()</strong> are returning a copy of the array - not a reference. By using <strong>reverse()</strong> after them we&apos;re only altering the copy.</blockquote><p>Or (a cleaner solution) using our best friend, the hero we all needed but didn&apos;t deserve him,<em> destructuring assignment</em>.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
const result = [...array].reverse();
console.dir(result); // Output: [&quot;&#x1F404;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;]
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;]</code></pre><blockquote><strong>NOTE.</strong> Here we are just destructuring our array into another array, which is going to be reversed. So it&apos;s basically also calling <strong>reverse()</strong> on a copy.</blockquote><p>We can also implement our own reverse function (this is only for <strong>absolute geeks</strong>).</p><p>Just kidding, we&apos;re not going to reinvent the wheel. I mean, you can, but... I&apos;m too busy and we have to cover some more methods. However, <a href="https://stackoverflow.com/questions/10168034/how-can-i-reverse-an-array-in-javascript-without-using-libraries">these guys</a> have time to do this, and you can check their thread for some funky solutions.</p><h2 id="how-to-add-new-elements-to-the-beginning-of-an-array">How to add new elements to the beginning of an array?</h2><p>If JavaScript methods were people,<strong> push()</strong> and <strong>shift()</strong> would be a couple with a kid named <strong>unshift()</strong>. <strong>unshift()</strong> like <strong>push()</strong> will add new elements to the array but at the beginning.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
array.unshift(&quot;&#x1F409;&quot;, &quot;&#x1F413;&quot;);
console.dir(array); // Output: [&quot;&#x1F409;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;]</code></pre><p>And like <strong>push()</strong> it also accepts more than one element.</p><pre><code class="language-javascript">const array1 = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;];
const array2 = [&quot;&#x1F40E;&quot;, &quot;&#x1F404;&quot;];
array1.unshift(...array1);
console.dir(array1); // Output: [&quot;&#x1F409;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;]</code></pre><p>Also, we can use destructuring to merge an array to the beginning of another.</p><p>Also similarly to <strong>push()</strong>, <strong>unshift()</strong> returns the new <strong>length </strong>of the array.</p><pre><code class="language-javascript">const array = [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;];
console.dir(array.unshift(&quot;&#x1F413;&quot;)); // Output: 4
console.dir(array); // Output: [&quot;&#x1F413;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;]</code></pre><h2 id="how-to-sort-an-array-in-javascript">How to sort an array in JavaScript?</h2><p>Sorting in JS is achieved with the <strong>sort()</strong> method. It utilizes an in-place algorithm so it doesn&apos;t copy the array, it alters the original.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
array.sort();
console.dir(array); // Output: [&quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;]</code></pre><p>If we want to keep the original we can do the same trick that we have done with <strong>reverse()</strong>.</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
const result = array.slice().sort();
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;]
console.dir(result); // Output: [&quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;]</code></pre><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
const result = [...array].sort();
console.dir(array); // Output: [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;]
console.dir(result); // Output: [&quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;]</code></pre><blockquote><strong>NOTE</strong>. Emojis are just unicode characters and every emoji has it&apos;s unique code. For example &#x1F404; is U+1F404 and &#x1F409; is U+1F409. The algorithm is going to sort by this codes.</blockquote><p>By default, this method sorts the elements using an ascending order - from lower to higher. If we want to sort in descending order we can write our own <em>compare function</em> (more on that in a moment) or just <strong>reverse() </strong>the sorted array (as it&apos;s more performant).</p><pre><code class="language-javascript">const array = [&quot;&#x1F405;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F409;&quot;];
array.sort().reverse();
console.dir(array); // Output: [&quot;&#x1F42C;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F404;&quot;]</code></pre><p>The default behavior of the <strong>sort()</strong> method causes also a very interesting problem, let&apos;s try to sort an array consisting of only numbers.</p><pre><code class="language-javascript">const array = [3, 45, 12, 1, 78, 369];
array.sort();
console.dir(array); // Output: [1, 12, 3, 369, 45, 78]</code></pre><p>It provides us with one conclusion.</p><figure class="kg-card kg-image-card"><img src="https://blog.danieo.me/content/images/2021/08/26a.jpg" class="kg-image" alt="cat standing in snow" loading="lazy" width="680" height="560" srcset="https://blog.danieo.me/content/images/size/w600/2021/08/26a.jpg 600w, https://blog.danieo.me/content/images/2021/08/26a.jpg 680w"></figure><p>This is because by default sort is converting the elements to strings and comparing them in UTF-16. So when comparing words like &quot;water&quot; and &quot;fire&quot;, &quot;fire&quot; comes first but when converting numbers to strings like 100 and 5 we end up with &quot;100&quot; coming before &quot;5&quot;. To solve this we need to provide our own <em>compare function</em> as the first argument.</p><pre><code class="language-javascript">const array = [3, 45, 12, 1, 78, 369];
array.sort((first, second) =&gt; first - second);
console.dir(array); // Output: [1, 3, 12, 45, 78, 369]</code></pre><p>Ah, much better.</p><blockquote><strong>NOTE.</strong> We use <code>first - second</code> rather than <code>first &gt; second</code> because it&apos;s more performant.</blockquote><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://blog.danieo.me/content/images/2021/08/Screenshot-2021-08-12-at-19-22-17-JSBEN-CH-Benchmarking-for-JavaScript--.png" class="kg-image" alt="Benchmark result - sort using arithmetics is faster than sort using comparison" loading="lazy"><figcaption>Benchmark performed using jsben.ch on an array with 10 000 random integers from 0 to 9999</figcaption></figure><p>The problem with sorting number arrays is not our only concern. If you&apos;re French, Polish, German, Czech, Spanish or a citizen of another country whose native language has some letters with diacritics and you want to compare some local strings... well your life is not easy then. Here&apos;s hows <strong>sort()</strong> is working with accent letters.</p><pre><code class="language-javascript">const array = [&quot;turku&#x107; podjadek&quot;, &quot;konik polny&quot;, &quot;komar&quot;, &quot;mucha&quot;, &quot;&#x107;ma&quot;];
array.sort();
console.dir(array); // Output: [&quot;komar&quot;, &quot;konik polny&quot;, &quot;mucha&quot;, &quot;turku&#x107; podjadek&quot;, &quot;&#x107;ma&quot;]</code></pre><p>This example is using some Polish insect names. The words with an accent are just put at the end. For example &quot;&#x107;ma&quot; should be first but it&apos;s last. To fix this we need to provide our own <em>compare function</em> again.</p><pre><code class="language-javascript">const array = [&quot;turku&#x107; podjadek&quot;, &quot;konik polny&quot;, &quot;komar&quot;, &quot;mucha&quot;, &quot;&#x107;ma&quot;];
array.sort((first, second) =&gt; first.localeCompare(second));
console.dir(array); // Output: [&quot;&#x107;ma&quot;, &quot;komar&quot;, &quot;konik polny&quot;, &quot;mucha&quot;, &quot;turku&#x107; podjadek&quot;]</code></pre><p>Now it&apos;s working. <strong>localeCompare()</strong> checks if the reference string comes after or before the string given.</p><h2 id="how-to-get-firstlastany-n-elements-from-an-array">How to get first/last/any n elements from an array?</h2><p><strong>slice()</strong> is the solution you&apos;re looking for. It accepts two arguments, the start index and the end index, both are optional, but when we provide neither of them - nothing happens. Here are some useful snippets.</p><h3 id="get-the-first-3-elements-of-an-array">Get the first 3 elements of an array</h3><pre><code class="language-javascript">const array = [&quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;];
const result = array.slice(0, 3);
console.dir(result); // Output: [&quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;]</code></pre><h3 id="get-the-last-element-of-an-array">Get the last element of an array</h3><pre><code class="language-javascript">const array = [&quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;];
const result = array.slice(-1);
console.dir(result); // Output: [&quot;&#x1F42C;&quot;]</code></pre><h3 id="get-the-second-half-of-an-array">Get the second half of an array</h3><pre><code class="language-javascript">const array = [&quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;];
const result = array.slice(array.length / 2);
console.dir(result); // Output: [&quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;]</code></pre><h3 id="get-the-first-half-of-an-array">Get the first half of an array</h3><pre><code class="language-javascript">const array = [&quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;];
const result = array.slice(0, array.length / 2);
console.dir(result); // Output: [&quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;]</code></pre><h3 id="get-elements-after-the-fourth-element">Get elements after the fourth element</h3><pre><code class="language-javascript">const array = [&quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;];
const result = array.slice(4);
console.dir(result); // Output: [&quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;]</code></pre><h3 id="get-a-slice-of-the-array">Get a slice of the array</h3><pre><code class="language-javascript">const array = [&quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;];
const result = array.slice(2, 4);
console.dir(result); // Output: [&quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;]</code></pre><p>As you can see, <strong>slice()</strong> can do many things. </p><h2 id="how-to-flatten-arrays">How to flatten arrays?</h2><p>Flattening means reducing the dimensions of an array. For example, if we got a two-dimensional array we can reduce it to only one dimension using <strong>flat()</strong>.</p><pre><code class="language-javascript">const array = [[&quot;&#x1F413;&quot;, &quot;&#x1F404;&quot;], [&quot;&#x1F405;&quot;, &quot;&#x1F412;&quot;]];
const result = array.flat();
console.dir(result); // Output: [&quot;&#x1F413;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F412;&quot;]</code></pre><p>Flattening doesn&apos;t affect the original array. It&apos;s copying its values.</p><p>By default <strong>flat()</strong> is going to flatten only one dimension. If you need to flatten a three (or more) dimensional array to just one dimension you have to provide the <strong>depth </strong>argument.</p><pre><code class="language-javascript">const array = [[&quot;&#x1F413;&quot;, &quot;&#x1F404;&quot;], [&quot;&#x1F405;&quot;, [&quot;&#x1F412;&quot;, &quot;&#x1F412;&quot;]]];
const result = array.flat(2);
console.dir(result); // Output: [&quot;&#x1F413;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F412;&quot;]</code></pre><h2 id="how-to-copy-elements-within-an-array">How to copy elements within an array?</h2><p>Sometimes you want to copy an element from one position to another. For this, you can use <strong>copyWithin()</strong>. Like <strong>slice()</strong> this method has many possible use cases.</p><h3 id="copy-first-two-elements-to-the-last-two-elements">Copy first two elements to the last two elements</h3><pre><code class="language-javascript">const array = [&quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;];
array.copyWithin(-2);
console.dir(array); // Output: [&quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;]</code></pre><h3 id="replacing-one-value-with-another">Replacing one value with another</h3><pre><code class="language-javascript">const array = [&quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;];
array.copyWithin(2, 0, 1);
console.dir(array); // Output: [&quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;]</code></pre><p>Here we replaced the &#x1F413; on index 2, with the piece that goes from index 0 to index 1, which is the <em>&#x1F409;. </em>By changing the second argument to 2 we would also affect the &#x1F42C;, basically inserting the <em>&#x1F409; </em>and <em>&#x1F412; </em>on the positions where<em> </em>&#x1F413; and &#x1F42C; were.</p><pre><code class="language-javascript">const array = [&quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F413;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;];
array.copyWithin(2, 0, 2);
console.dir(array); // Output: [&quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F409;&quot;, &quot;&#x1F412;&quot;, &quot;&#x1F404;&quot;, &quot;&#x1F405;&quot;]</code></pre><hr><p>For now - that&apos;s all. We&apos;ve discussed all methods from the Array prototype that are used to alter arrays. This article series is going to be divided into 3 parts, the next part will deal with array iterators and looping through them, and the third would be about searching elements in arrays.</p><h2 id="rest-of-the-series">Rest of the series</h2><ul><li><a href="https://blog.danieo.me/javascript-array-methods-2/">JavaScript array methods 2/3 - iterating arrays</a></li></ul>]]></content:encoded></item><item><title><![CDATA[A brief introduction to JavaScript arrays]]></title><description><![CDATA[<p>What is an array? How to create one? How to retrieve values from them? And more... just a short recap for beginners.</p><hr><p>JavaScript arrays are <strong>objects</strong>, so they&apos;re not a separate type like in other languages. These objects hold a collection of elements. To create an empty array</p>]]></description><link>https://blog.danieo.me/a-brief-introduction-to-javascript-arrays/</link><guid isPermaLink="false">611592cb704a6528a5571e51</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Tutorials]]></category><dc:creator><![CDATA[Daniel Budziński]]></dc:creator><pubDate>Thu, 12 Aug 2021 22:40:00 GMT</pubDate><content:encoded><![CDATA[<p>What is an array? How to create one? How to retrieve values from them? And more... just a short recap for beginners.</p><hr><p>JavaScript arrays are <strong>objects</strong>, so they&apos;re not a separate type like in other languages. These objects hold a collection of elements. To create an empty array we got two ways. First, we can use the Array constructor.</p><pre><code class="language-javascript">const array = Array();</code></pre><p>But the <strong>preferable </strong>method is using the array literal notation.</p><pre><code class="language-javascript">const array = [];</code></pre><hr><p>Arrays can be initialized with some values.</p><pre><code class="language-javascript">const array = [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;];
console.dir(array); // Output: [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;]</code></pre><p>We can also achieve this with the constructor</p><pre><code class="language-javascript">const array = Array(&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;);
console.dir(array); // Output: [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;]</code></pre><p>But there comes a problem with this method. Let&apos;s assume that we want to create a single element array and that element would be the number 5.</p><pre><code class="language-javascript">const array = Array(5);
console.dir(array); // Output: [undefined, undefined, undefined, undefined, undefined]</code></pre><p>We get an array with 5 <em>undefined </em>elements. To fix this we can use the <strong>Array.of()</strong> method.</p><pre><code class="language-javascript">const array = Array.of(5);
console.dir(array); // Output: [5]</code></pre><pre><code class="language-javascript">const array = Array.of(5, 6, 7);
console.dir(array); // Output: [5, 6, 7]</code></pre><p>Much better. </p><hr><p>We can also fill empty arrays using the <strong>fill()</strong> method.</p><pre><code class="language-javascript">const array = Array(4);
array.fill(1);
console.dir(array); // Output: [1, 1, 1, 1]</code></pre><p>We got an array with 4 empty elements so we filled them with 1. Filling can be also done only for certain indexes by passing two more arguments - start and end index.</p><pre><code class="language-javascript">const array = Array(4);
array.fill(1, 0, 2);
console.dir(array); // Output: [1, 1, undefined, undefined]</code></pre><hr><p>JavaScript has other data structures like <strong>Maps </strong>and <strong>Sets </strong>or iterable objects like<strong> String </strong>or <strong>NodeList. </strong> We can convert them to array using <strong>Array.from()</strong>.</p><h3 id="string-to-array">String to Array</h3><pre><code class="language-javascript">const array = Array.from(&quot;Hello World!&quot;);
console.dir(array); // Output: [&quot;H&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;, &quot; &quot;, &quot;W&quot;, &quot;o&quot;, &quot;r&quot;, &quot;l&quot;, &quot;d&quot;, &quot;!&quot;]</code></pre><h3 id="nodelist-to-array">NodeList to Array</h3><pre><code class="language-javascript">const nodeList = document.querySelectorAll(&apos;.element&apos;);
const array = Array.from(nodeList);</code></pre><h3 id="setmap-to-array">Set/Map to Array</h3><pre><code class="language-javascript">const set = new Set();
set.add(1);
set.add(3);
const array = Array.from(set);
console.dir(array); // Output: [1, 3]</code></pre><pre><code class="language-javascript">const map = new Map();
map.set(&apos;key1&apos;, 1);
map.set(&apos;key2&apos;, 2);
const array = Array.from(map);
console.dir(array); // Output: [[&apos;key1&apos;, 1], [&apos;key2&apos;, 2]]</code></pre><hr><p>As you can see in the Set/Map example - JavaScript arrays can be <strong>multi-typed</strong> and <strong>multi-dimensional</strong>. So using different types in one array is possible...</p><pre><code class="language-javascript">const array = [1, &quot;text&quot;, null, {}];
console.dir(array); // Output: [1, &quot;text&quot;, null, {}]</code></pre><p>...just like creating matrices</p><pre><code class="language-javascript">const matrix = [
  [0, 1, 2],
  [0, 3, 4],
  [1, 9, 8],
];</code></pre><hr><p>Values from an array can be retrieved by referencing their index</p><pre><code class="language-javascript">const array = [1, 2, 3];
console.dir(array[1]); // Output: 2

const matrix = [
  [0, 1, 2],
  [0, 3, 4],
  [1, 9, 8],
];
console.dir(matrix[1][2]); // Output: 4</code></pre><hr><p>Every array has its length which can be found under the <strong>length </strong>property.</p><pre><code class="language-javascript">const array = [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;];
console.dir(array.length); // Output: 3</code></pre><p><strong>length </strong>is settable which means you can resize the array by changing its value.</p><pre><code class="language-javascript">const array = [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;];
array.length = 5;
console.dir(array); // Output: [&quot;&#x1F412;&quot;, &quot;&#x1F42C;&quot;, &quot;&#x1F405;&quot;, undefined, undefined]
array.length = 1;
console.dir(array); // Output: [&quot;&#x1F412;&quot;]
</code></pre><p>As you can see if the new value for length is bigger than the old one, the array will extend but all of the new values are going to be <em>undefined</em>.</p>]]></content:encoded></item><item><title><![CDATA[Hello World!]]></title><description><![CDATA[The very first post on this blog! An introduction of the project and of myself.]]></description><link>https://blog.danieo.me/hello-world/</link><guid isPermaLink="false">6106c868704a6528a5571857</guid><category><![CDATA[Other]]></category><dc:creator><![CDATA[Daniel Budziński]]></dc:creator><pubDate>Tue, 03 Aug 2021 21:40:56 GMT</pubDate><content:encoded><![CDATA[<p>This is a pioneering post on this blog. The very first, but not the last! I created this blog as an experiment. In short - its purpose is to give me some space on the internet to share and enrich my knowledge. Occasionally I am also going to write some of my thoughts on the IT industry (and maybe my personal stories). If you want to know more about this project, &#xA0;keep reading. If not - well, you can check my other articles!</p><hr><p>After this short presentation of this blog, I should introduce myself.</p><p>My name is Daniel, I&apos;m from Poland. I program since I went to ground school. My commercial activity had its major start 2+ years ago when I got my first job as a developer. Before, I&apos;ve done some freelance jobs (mostly when I needed extra money). At that time programming was for me just a hobby. I created games, websites (my first websites were via www games &#x1F601;) and played a bit with Arduino. Now I work as a JavaScript developer and study mechatronics microsystems engineering at Wroc&#x142;aw University of Science and Technology.</p><p>As said earlier, this blog was created to share and enrich my knowledge. I wanted to share with people the things that I learned and help someone avoid the mistakes I have made (or spend less time on solving problems than I spent...). For me it is going to help me consolidate and update the knowledge I&apos;m sharing and improve my English skills.</p><p>Hope we will have a good time together and be better programmers in the future!</p>]]></content:encoded></item></channel></rss>