<?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 Intspirit Ltd on Medium]]></title>
        <description><![CDATA[Stories by Intspirit Ltd on Medium]]></description>
        <link>https://medium.com/@intspirit?source=rss-5e5426eda6b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E_ORlQ7tdEMlHJVQA_6tbw.png</url>
            <title>Stories by Intspirit Ltd on Medium</title>
            <link>https://medium.com/@intspirit?source=rss-5e5426eda6b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 00:40:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@intspirit/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[Understanding the browser’s Event Loop for building high-performance web applications. Part 2.]]></title>
            <link>https://intspirit.medium.com/understanding-the-browsers-event-loop-for-building-high-performance-web-applications-part-2-234a78f4a3e7?source=rss-5e5426eda6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/234a78f4a3e7</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Intspirit Ltd]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 07:15:53 GMT</pubDate>
            <atom:updated>2023-10-24T08:30:38.400Z</atom:updated>
            <content:encoded><![CDATA[<p>A deep dive into the Event Loop: task priorities, dealing with long tasks, using the browser idle time, scheduling microtasks, counting the number of event loops on a page.</p><figure><img alt="Hermione and Ron talking about web application optimization: — Hermione, why is your app so fast? Face it, it uses a Time-Turner to process all the user’s requests. — No. I simply break up long tasks and have time to answer all user requests." src="https://cdn-images-1.medium.com/max/1024/1*SvYfePChsMX4dg6-Wvpt6Q.png" /></figure><p>In a previous <a href="https://medium.com/@intspirit/understanding-the-browsers-event-loop-for-building-high-performance-web-applications-part-1-fe4b573a1520">blog post</a>, we looked at the Event Loop algorithm from a bird’s eye view. In this article, we’ll take a deeper look at the mechanisms of the Event Loop and how to use its features to write efficient code.</p><h3>Deep into the task.</h3><p>As we said before, a task is a piece of work that the browser needs to do.</p><p>Each task has an additional property — source. Which defines the type of task.</p><p>For example, keyboard, mouse, and other events sent in response to user interactions have user interaction sources. Tasks related to DOM manipulation, such as inserting an element into a document, have DOM manipulation task sources. There are others: networking, navigation, etc.</p><p>The browser can choose tasks with which source to give preference. To do this, browsers implement not one, but several queues. For example, a browser can make a separate queue for tasks with a user interaction source and give preference to it, thus increasing the performance of user interaction operations. (All modern browsers usually do this.)</p><p>It’s good news. Even if you have quite a few tasks, the browser will prioritize the important ones, so performance won’t be affected.</p><h3>Long tasks.</h3><p>The bad news is you can still mess up the user experience if your tasks are too long. Executing a task blocks all other actions of this thread — for example, responding to user actions such as mouse clicks or scrolls. Therefore, long tasks have a negative impact on performance and should be broken down into smaller ones.</p><p>To find out such long tasks, use the Chrome Dev tools.</p><p>Go to Chrome Dev tools -&gt; Performance tab -&gt; click Record -&gt; perform actions on the page that use the code you want to test (e.g. page reload or a button click) -&gt; stop recording and analyze the result.</p><p>By zooming in, you can distinguish between individual tasks. For example, this is what a single call to setInterval looks like:</p><figure><img alt="Screenshot of a task from the chrome dev tool -&gt; performance tab." src="https://cdn-images-1.medium.com/max/1024/1*HHuC9npznTk2bWRUd_hKRg.png" /><figcaption>Screenshot of a task from the chrome dev tool -&gt; performance tab.</figcaption></figure><p>Chrome marks long tasks with a red stroke and a pop-up, which indicates the duration of the task:</p><figure><img alt="Screenshot of a long task from the chrome dev tool -&gt; performance tab." src="https://cdn-images-1.medium.com/max/1024/1*GeG0TcjDJ1NcQ7EPABaeVw.png" /><figcaption>Screenshot of a long task from the chrome dev tool -&gt; performance tab.</figcaption></figure><p>When long tasks are found, you need to break them into small ones. How to do it?</p><h3>Quiz 1.</h3><p>We have refactored 3 functions that were taking too long to execute. Which function will now give the browser time to respond to user input?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/037bf597dd066486fb4e55b3fdbb0e2a/href">https://medium.com/media/037bf597dd066486fb4e55b3fdbb0e2a/href</a></iframe><p><a href="https://t.me/intspirit/805">Try yourself</a></p><p>Explanation.</p><p>If your function does a lot of work, even if it is broken into subfunctions, it’s all a single task, during which the browser cannot be interrupted. Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efffc5db6bd11021ec00a4a7821594fa/href">https://medium.com/media/efffc5db6bd11021ec00a4a7821594fa/href</a></iframe><p>However, this kind of refactoring should not be underestimated. Breaking up a large function is still productive. The browser makes useful optimizations with our code. They are easier to implement on small functions. In addition, sometimes optimization is followed by deoptimization. Optimization and deoptimization can occur several times with the same function. And the larger the function, the more resources this process will require.</p><p>The Promise callback is queued for microtasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a77ffdbcc5e8a194cd4dc46f39cfb48/href">https://medium.com/media/3a77ffdbcc5e8a194cd4dc46f39cfb48/href</a></iframe><p>Microtasks are executed immediately after the execution of the current task, which means that the browser will not be able to interrupt to process the user action.</p><p>A long task can be broken into smaller ones using setTimeout. This way, in between chunks of one big task, the browser can do important work, such as responding to user input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/410f841bc59a1cb6eb313d93c91c9130/href">https://medium.com/media/410f841bc59a1cb6eb313d93c91c9130/href</a></iframe><p>However, this method is not very convenient when we need to break up a long loop.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/672f028e321c0df6f1a390d25f4f81e6/href">https://medium.com/media/672f028e321c0df6f1a390d25f4f81e6/href</a></iframe><p>On my computer, this script runs for 520ms:</p><figure><img alt="Screenshot of a long task from the chrome dev tool -&gt; performance tab." src="https://cdn-images-1.medium.com/max/1024/0*EPEAG7zs-RDq8UuM" /><figcaption>Screenshot of a very long task from the chrome dev tool -&gt; performance tab.</figcaption></figure><p>In such a case, we can use a combination of Promise and setTimeout:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ade8dfd6373d67e8df80fde81573cea8/href">https://medium.com/media/ade8dfd6373d67e8df80fde81573cea8/href</a></iframe><p>Now, instead of one long task, we have many small ones between which the browser can perform other important tasks:</p><figure><img alt="Screenshot of chrome dev tools perdormance tab. Now the cycle is divided into several tasks." src="https://cdn-images-1.medium.com/max/1024/1*VT3wUi5tQr1jXDFI-VzzXg.png" /><figcaption>Screenshot of chrome dev tools perdormance tab. Now the cycle is divided into several tasks.</figcaption></figure><p>How does this code work?</p><p>When the pause function is called:</p><ol><li>The code inside the Promise is executed synchronously, causing the setTimeout callback to be put on the task queue.</li><li>The pause function is popped off the stack and execution continues from where it was called.</li><li>At this point, the browser encounters the await keyword. It pauses the execution of the function, the rest of the function will be executed as a microtask after the promise is resolved.</li><li>Now the browser returns to the line where the foo function was called from. Since this function call does not have an await, the browser executes the rest of the code.</li><li>When the task is completed, the browser picks up the next one. This is when the browser can do important work such as responding to a click event.</li><li>When there is no more important work left, the browser will execute our setTimeout callback.</li><li>Executing the setTimeout callback will resolve the promise, which will cause the browser to jump back to executing the foo function.</li></ol><p>There is also a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Scheduler">Scheduler API</a> for the same purpose. It is more flexible and allows you to explicitly prioritize tasks. But it doesn’t have great <a href="https://caniuse.com/mdn-api_scheduler_posttask">support</a> yet.</p><p>Using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Scheduler">Scheduler API</a> this code can be further improved if it is interrupted not after a certain number of iterations, but when necessary — i.e. when the browser needs to respond to user input. There is a special method for this, <a href="https://developer.mozilla.org/en-US/docs/Web/API/Scheduling/isInputPending">isInputPending</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eeed5656cf6d3360d3e94a2a53e14b4/href">https://medium.com/media/6eeed5656cf6d3360d3e94a2a53e14b4/href</a></iframe><p>Now the cycle will be interrupted only when necessary. For example, if the user made a click that needs to be processed.</p><p>For browsers without support for this feature, you can have a fallback for interrupting a long loop by timer.</p><h3>Schedule Microtasks.</h3><p>The main difference between a microtask and a task is that a microtask is executed immediately after the current task and no other code can be executed between them.</p><p>For example, if your script encounters a setTimeout with zero delay, you cannot guarantee that its callback will be executed immediately after the script. If an event is fired during script execution, the browser will give priority to the event handler.</p><p>On the other hand, if it is not a setTimeout but a microtask, it will be executed first.</p><p>Thus, when you need to perform an action immediately after some task, you should schedule a microtask.</p><p>To schedule a microtask, developers sometimes use a Promise that resolves immediately. However, this method has several disadvantages: it is a trick and it requires additional overhead to create and clean up the promise.</p><p>Therefore, if you are faced with the need to create a microtask, use the queueMicrotask() function.</p><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask">MDN</a> says:</p><p>The queueMicrotask() method, which is exposed on the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">Window</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">Worker</a> interface, queues a microtask to be executed at a safe time prior to control returning to the browser’s event loop.</p><p>Syntax:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7f88be9d154874b9d4aed01963aa13d/href">https://medium.com/media/f7f88be9d154874b9d4aed01963aa13d/href</a></iframe><p>Why might you need to create a microtask? For example, to batch operations. Look at this example from <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide">MDN</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7440643e37dd76f933da9688a374f80f/href">https://medium.com/media/7440643e37dd76f933da9688a374f80f/href</a></iframe><p>No matter how many times the sendMessage() function is called, messages will only be sent once after all calls (made within the same task).</p><h3>Idle period.</h3><p>When all tasks and microtasks are completed, the browser enters the so-called idle period. And for those who want to write efficient code, you need to take advantage of this. The idle period is the perfect time to do low priority work.</p><p>To schedule a task in the browser’s idle period, use the method:</p><p>window.requestIdleCallback(callback, options)</p><p>In the options, you can pass the timeout parameter — the maximum number of milliseconds after which the callback should be called. If after this time the callback has not yet been called, the task to execute the callback will be queued into the event loop, even if this is going to negatively affect the performance.</p><p>Let’s look at some examples.</p><h3>Quiz 1.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e31dddaf104396a0f976526e6f90b7/href">https://medium.com/media/d7e31dddaf104396a0f976526e6f90b7/href</a></iframe><p><a href="https://t.me/intspirit/727">Check yourself</a></p><p>Explanation.</p><ul><li>After the script is executed, it is the turn of microtasks. We have one microtask waiting — queueMicrotask callback. Output: 4.</li><li>Then the first task in the task queue. This is a setTimeout callback that outputs 2.</li><li>Since there are no more microtasks, the browser executes the task again — a second setTimeout callback. Output: 3.</li></ul><p>Both queues are empty, which means that it’s time to execute requestIdleCallback. The result will be as follows: 4, 2, 3, 1</p><h3>Quiz 2.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68854a92c2949170525297885e243c45/href">https://medium.com/media/68854a92c2949170525297885e243c45/href</a></iframe><p><a href="https://t.me/intspirit/729">Check yourself</a></p><p>Explanation.</p><ul><li>The event loop is idle the first second after the script is executed, so it has time to execute the requestIdleCallback callback.</li><li>The body of the promise is executed synchronously. Thus, of the two setTimeouts, the browser will put setTimeout inside the promise into the task queue first. This means it will also be executed first.</li><li>Executing this setTimeout callback creates a new microtask — Promise callback.</li><li>The task is completed. It’s time to complete all the microtasks. The Promise callback created in the previous step will be executed.</li><li>The browser jumps to the last task — the remaining setTimeout callback. So the result is: requestIdleCallback, promise, timeout</li></ul><p>More non-trivial challenges for understanding the Event Loop algorithm in the first part of this series of articles:</p><p><a href="https://intspirit.medium.com/understanding-the-browsers-event-loop-for-building-high-performance-web-applications-part-1-fe4b573a1520">Understanding the browser’s Event Loop for building high-performance web applications. Part 1.</a></p><h3>Do you know how many event loops are in your app?</h3><p>Try to answer the question: Will the heavy synchronous code inside the iframe delay the execution of the setTimeout cb in the parent script?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7ff1616072a0f0e982e48a8287a2394/href">https://medium.com/media/d7ff1616072a0f0e982e48a8287a2394/href</a></iframe><p><a href="https://t.me/intspirit/801">Check yourself</a></p><p>To answer this question, the only thing you need to know is whether the iframe and the parent script share the same event loop or have different ones.</p><p>If they share an event loop, then the heavy synchronous operation blocks the parent script as if it was in it. Otherwise, this operation will block iframe tasks only.</p><p>It turns out that iframes with the same origin share an event loop with the parent. Moreover, even different tabs of the same origin can share the same event loop. For example, if the second tab is opened with window.open().</p><p>This is a case where you need to be especially careful with long running tasks, because they can block the rendering of your other window.</p><p>However, your page can still have more than one Event Loop. Each individual thread has its own event loop. Worklets and workers have their own event loop.</p><p><strong>In conclusion.</strong></p><p>As always, we want to encourage you to keep learning the language you write every day and let’s make IT better!</p><p>Subscribe to the <a href="https://t.me/intspirit">telegram-channel</a> to learn:</p><ul><li>how modern JavaScript works</li><li>what optimizations are made by browsers and how to use them</li><li>how to reduce memory consumption and improve application performance on mobile devices</li><li>how to avoid memory leaks</li><li>how to help the browser render efficiently and much more.</li></ul><p>And most importantly, all this with the help of quizzes, which make the assimilation of the material easy.</p><p>Follow us on <a href="https://intspirit.medium.com/">Medium</a> to not to miss new stuff.</p><p>Pop into our <a href="https://www.linkedin.com/company/intspirit">LinkedIn</a> for other cool things we do.</p><h3>Resources.</h3><ol><li><a href="https://html.spec.whatwg.org/multipage/webappapis.html#event-loops">https://html.spec.whatwg.org/multipage/webappapis.html#event-loops</a></li><li><a href="https://web.dev/optimize-long-tasks/">https://web.dev/optimize-long-tasks/</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide">https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback">https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask">https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Scheduler">https://developer.mozilla.org/en-US/docs/Web/API/Scheduler</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Scheduling/isInputPending">https://developer.mozilla.org/en-US/docs/Web/API/Scheduling/isInputPending</a></li><li><a href="https://t.me/intspirit">https://t.me/intspirit</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=234a78f4a3e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the browser’s Event Loop for building high-performance web applications. Part 1.]]></title>
            <link>https://intspirit.medium.com/understanding-the-browsers-event-loop-for-building-high-performance-web-applications-part-1-fe4b573a1520?source=rss-5e5426eda6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe4b573a1520</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Intspirit Ltd]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 06:10:54 GMT</pubDate>
            <atom:updated>2025-12-12T11:03:06.130Z</atom:updated>
            <content:encoded><![CDATA[<p>The most common interview question and the essential base for writing an efficient code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDR-Kkn4SdP8k-nOHiOOBA.png" /><figcaption>Senior Harry Potter.</figcaption></figure><p>“How does the Browser Event Loop work?” This question can be asked in almost every JavaScript interview. Interviewers are often scolded for bad questions, but hardly anyone would argue that this question is just great! A good knowledge of the event loop gives you an understanding of how the browser will handle the code and how not to put a spoke in the wheel, but to help it be efficient so that users of your applications get the best experience.</p><p>An event loop is similar to a project manager. It coordinates events, rendering, network requests, user interactions, and all your asynchronous code.</p><p>Below are a few challenges from our <a href="https://t.me/intspirit">telegram channel</a> with JavaScript quizzes. Interviewers love to ask questions like this. Check yourself. Don’t worry if you don’t understand how this code works, we’ll cover it further in the article.</p><h3>Quiz 1.</h3><p>This is the simplest example that demonstrates how the event loop works. By the way, this is also the most common interview challenge. Therefore, you could already meet this quiz in our previous blog post on the most difficult interview questions:</p><p><a href="https://intspirit.medium.com/the-most-failed-javascript-interview-questions-849664e5bee">The most failed JavaScript interview questions</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d46ed56e7c36b4e71a83e1e94a7f26e/href">https://medium.com/media/7d46ed56e7c36b4e71a83e1e94a7f26e/href</a></iframe><p><a href="https://t.me/intspirit/566">Try yourself</a></p><h3>Quiz 2.</h3><p>This quiz is a little more confusing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ede9e65b156cd3c5da0a286019a0d70e/href">https://medium.com/media/ede9e65b156cd3c5da0a286019a0d70e/href</a></iframe><p><a href="https://t.me/intspirit/719">Try yourself</a></p><h3>Quiz 3.</h3><p>This quiz at first glance is similar to the previous ones. However, only 17% of the audience of our telegram channel (which is incredibly strong in JavaScript, judging by the answers to other quizzes) managed to answer correctly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c37d7b2b25fe57753bb9f8cc280edb44/href">https://medium.com/media/c37d7b2b25fe57753bb9f8cc280edb44/href</a></iframe><p><a href="https://t.me/intspirit/723">Try yourself</a></p><p>To understand the code in these examples, let’s take a deeper look at the event loop.</p><p>If you answered all questions correctly (and more importantly, you can explain the result) — congratulations! Feel free to skip the “How the Event Loop works” part and go to the “Rendering” section. We will definitely surprise you there.</p><h3>How the Event Loop works.</h3><p>The event loop operates on a queue of tasks (or macro tasks) and microtasks.</p><p>A task (and a microtask) is a piece of work that the browser needs to do. In general, we can say that a task is a function.</p><p>Tasks examples:</p><ul><li>Script execution</li><li>Parsing html</li><li>SetTimeout callback</li><li>Callback on mouse click or any other event</li></ul><p>Microtasks are tasks that need to be performed immediately after the script is executed.</p><p>Microtasks examples:</p><ul><li>Promise callback</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver">Mutation Observer API</a></li></ul><p>We will look at the algorithm of the event loop, helping ourselves with a graphical example for clarity.</p><p>Consider the following tasks waiting to be executed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMXUBPu8gF_k0VsrE1irmQ.png" /><figcaption>Queues initial states.</figcaption></figure><p>To simplify, the event loop goes through the following steps indefinitely:</p><p>1. If there is at least one task in the task queue, get the first (oldest) task and execute it. This is the bar()function in our case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70qlhRInaUz4MjCatHIvHw.png" /><figcaption>There is one task <strong>foo()</strong> and two microtasks: <strong>baz()</strong> and <strong>qqz() </strong>waiting to be executed.</figcaption></figure><p>2. If there are tasks in the microtask queue, execute all tasks, starting with the oldest one. The qqz() function , then the baz() function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tyZiy5JEqERDJMVoeU_zA.png" /><figcaption>There is one task to execute: <strong>foo().</strong></figcaption></figure><p>3. Update the rendering.</p><p>As a result of repeating the steps, both queues will become empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OiXbIZ0wXcznwFRwQIT6Ww.png" /><figcaption>Both queues are empty now.</figcaption></figure><h3>Call stack.</h3><p>What happens to a task when it is picked up for execution? It is pushed onto the call stack. Let’s look at an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ae1c3ff84eca468d27ee025cec3a57f/href">https://medium.com/media/6ae1c3ff84eca468d27ee025cec3a57f/href</a></iframe><p>The first task that the browser faces is the execution of the script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2qh-kAr4qC8fx-euafGCA.png" /><figcaption>The first task: execute the <strong>script.</strong></figcaption></figure><p>The task that is taken by the browser for execution gets into the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0vTE9gS-TD1-Ue8xAcinA.png" /><figcaption>Execute: <strong>script.</strong></figcaption></figure><p>All functions that this code calls also get into the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QFpaI5rIf5glL_J6Vdxgmg.png" /><figcaption>Execute: <strong>foo().</strong></figcaption></figure><p>If a new task is created as a result of the function execution, it is placed in the task queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2ni8Q75DdgW50JymJA7LA.png" /><figcaption>Execute: <strong>setTimeout(() =&gt; console.log(‘timeout’)).</strong></figcaption></figure><p>When a function is executed, it is popped from the stack. (setTimeout in our case)</p><blockquote>In the “stack” data structure — the last in, the first one out. In the “queue” data structure, the opposite is true — first in, first out.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TISNnX_qZkv5eSIsRaOyMg.png" /><figcaption>Execute: <strong>bar().</strong></figcaption></figure><p>If a new microtask is created as a result of the function execution, it is placed in the microtask queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZsV58ym86VGYE-t9Vbhsw.png" /><figcaption>Execute: <strong>new Promise((resolve) =&gt; resolve()).then(() =&gt; console.log(‘promise’)).</strong></figcaption></figure><p>Next, Promise(), bar(), foo(), and script are popped off the stack in turn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgISmzai9R9H3qNzPGaBmg.png" /><figcaption><strong>Promise(), </strong><strong>bar(), </strong><strong>foo()</strong>, and <strong>script</strong> are popped off the stack.</figcaption></figure><p>When the stack becomes empty, the task is completed. After that, it is the turn to execute all the microtasks that have accumulated during the execution of the task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PG13VlW91z2ad4yaCfrwwg.png" /><figcaption>Execute: <strong>() =&gt; console.log(‘promise’).</strong></figcaption></figure><p>When the stack is empty and no microtasks are left in the queue, the browser can move on to the next task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqDUwsRHMoIkThOAsgH5sQ.png" /><figcaption>Execute:<strong> () =&gt; console.log(‘timeout’).</strong></figcaption></figure><p>When both queues are empty, the browser does nothing, waiting for new tasks.</p><p>Now we can go back to our quizzes and see what steps the browser will go through when executing them.</p><h3>Quiz 1. Explanation.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17cf25e9753be0b5b48eb77794defc53/href">https://medium.com/media/17cf25e9753be0b5b48eb77794defc53/href</a></iframe><p>Browser steps:</p><ol><li>The first task to execute is the script. The result of this step:</li></ol><ul><li>The setTimeout callback is added to the task queue.</li><li>The promise executor function res =&gt; { console.log(3); res(); } is executed synchronously. So, the output of this step: 2, 3, 5.</li><li>The promise callback is added to the microtask queue.</li></ul><p>2. Execute tasks from the microtask queue. Output: 4.</p><p>3. Execute the last task — setTimeout callback. Output: 1.</p><p>Result: 2, 3, 5, 4, 1.</p><h3>Quiz 2. Explanation.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ede9e65b156cd3c5da0a286019a0d70e/href">https://medium.com/media/ede9e65b156cd3c5da0a286019a0d70e/href</a></iframe><p>Browser steps:</p><ol><li>Execute the script. The result of this step:</li></ol><ul><li>Both setTimeout callbacks are added to the task queue in the order in which they occur in the code.</li><li>The callback of the second promise is added to the microtask queue.</li></ul><p>2. Execute tasks from the microtask queue. Output: promise 2.</p><p>3. Execute the oldest task from the macrotask queue. The result of this step:</p><ul><li>Output: timeout 1.</li><li>The new promise callback is added to the microtask queue.</li></ul><p>4. Execute tasks from the microtask queue. Output: promise 1.</p><p>5. Execute the last macrotask. Output: timeout 2.</p><p>Result: promise 2, timeout 1, promise 1, timeout 2.</p><h3>Quiz 3. Explanation.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c37d7b2b25fe57753bb9f8cc280edb44/href">https://medium.com/media/c37d7b2b25fe57753bb9f8cc280edb44/href</a></iframe><p>Browser steps:</p><ol><li>Execute the script. The result of this step:</li></ol><ul><li>timeout 1 and timeout 2 callbacks are added to the task queue.</li><li>The promise executor function resolve =&gt; setTimeout(resolve) is executed synchronously. So one more setTimeout is added to the task queue.</li><li>Promise.resolve() resolves the promise immediately, its callback is added to the microtask queue. Because the first promise has not yet been fulfilled, its callback has not yet been added to the microtask queue.</li></ul><p>2. Execute tasks from the microtask queue. Output: promise 2.</p><p>3. Execute a task from the task queue, starting from the oldest task. Output: timeout 1.</p><p>4. Because the microtask queue is empty, execute the oldest task in the task queue again. As a result, () =&gt; console.log(‘promise 1’)function is added to the microtask queue.</p><p>5. Execute tasks from the microtask queue. Output: promise 1.</p><p>6. Execute a task from the task queue. Finally, we will see timeout 2 in the console.</p><p>Result: promise 2, timeout 1, promise 1, timeout 2.</p><h3>Rendering.</h3><p>Let’s take a closer look at the rendering step.</p><h3>Quiz 1.</h3><p>Try to guess what will be displayed on the screen:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbee18ea1d88f6cb78e922fe3be95aee/href">https://medium.com/media/bbee18ea1d88f6cb78e922fe3be95aee/href</a></iframe><p><a href="https://t.me/intspirit/786">Check yourself</a></p><p>According to <a href="https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame">MDN</a>:</p><p>The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation right before the next repaint.</p><p>In other words, the requestAnimationFrame() method is called right before the rendering step.</p><p>According to the algorithm, after the execution of the task (and all microtasks), the browser updates the rendering.</p><p>So, the first rendering is expected after the script execution. And then the order of displaying the letters on the screen is as follows: B, A, C. D will never be drawn to the screen because it shares one rendering step with the requestAnimationFrame callback, which will be executed last.</p><p>Thus, the user would see C on the screen. This is how this code works in Safari now.</p><p>However, browsers may skip the rendering step if they think it will not contain visual changes, or if they want to combine multiple tasks for optimization purpose. For example, a browser might decide to merge multiple timer callbacks together and skip rendering in between.</p><p>For this reason, most modern browsers executing this example will skip rendering after the script is executed, and bundle setTimeout callbacks. Thus, there will be only one rendering for three tasks. This small omission will dramatically change the final result. The only thing the browser will render is B.</p><p>To verify this, run the code, open chrome Dev Tools -&gt; Performance tab -&gt; click Record, refresh the page. You will only see one frame that has been drawn.</p><p>Such an inconsistent result can be not only between browsers, but also in the same browser from launch to launch. Therefore, such ambiguous code should be avoided.</p><h3>Quiz 2.</h3><p>In the code below, there are two buttons that animate the logo rotation 360 degrees. One button animates with setTimeout, the other with requestAnimationFrame. What animation do you think will rotate the logo 360 degrees faster?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48f4cabc30cf4e1623eedb94e6dd7cd7/href">https://medium.com/media/48f4cabc30cf4e1623eedb94e6dd7cd7/href</a></iframe><p><a href="https://t.me/intspirit/788">Check yourself</a></p><p>This is another example of a browser skipping a rendering step. The requestAnimationFrame() function is called every time before rendering, so it will be called exactly 360 times. In the setTimeout() case, the browser performs one rendering for multiple (3–4) setTimeout calls. Therefore, such an animation will run faster, and many frames will be skipped. See demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bM9NcN0g_zGypNCtpA45dg.gif" /><figcaption>No frames are skipped with requestAnimationFrame() animation. The setTimeout animation skips many frames.</figcaption></figure><p>Tip! Use the requestAnimationFrame() method for animations to avoid dropping frames.</p><p>Rendering process is a very interesting topic that is beyond the scope of this article. We will definitely write about it later. Subscribe so you don’t miss out.</p><p><strong>In conclusion.</strong></p><p>In this blog post, we took a bird’s eye view of the event loop algorithm. In Part 2, we looked at how to use loop event functions to write efficient code:</p><p><a href="https://intspirit.medium.com/understanding-the-browsers-event-loop-for-building-high-performance-web-applications-part-2-234a78f4a3e7">Understanding the browser’s Event Loop for building high-performance web applications. Part 2.</a></p><p>As always, we want to encourage you to keep learning the language you write every day and let’s make IT better!</p><p>Subscribe to the <a href="https://t.me/intspirit">telegram-channel</a> to learn:</p><p>- how modern JavaScript works<br>- what optimizations are made by browsers and how to use it<br>- how to reduce memory consumption and improve application performance on mobile devices<br>- how to avoid memory leaks<br>- how to help the browser render efficiently.</p><p>And most importantly, all this with the help of quizzes, which make the assimilation of the material easy.</p><p>Follow us on <a href="https://intspirit.medium.com/">Medium</a> to not miss new stuff.</p><p>Pop into our <a href="https://www.linkedin.com/company/intspirit">LinkedIn</a> for other cool things we do.</p><h3>Resources.</h3><ol><li><a href="https://html.spec.whatwg.org/multipage/webappapis.html#event-loops">https://html.spec.whatwg.org/multipage/webappapis.html#event-loops</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame">https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame</a></li><li><a href="https://t.me/intspirit">https://t.me/intspirit</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe4b573a1520" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The most failed JavaScript interview questions]]></title>
            <link>https://intspirit.medium.com/the-most-failed-javascript-interview-questions-849664e5bee?source=rss-5e5426eda6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/849664e5bee</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Intspirit Ltd]]></dc:creator>
            <pubDate>Thu, 09 Mar 2023 12:20:20 GMT</pubDate>
            <atom:updated>2023-09-04T12:11:02.080Z</atom:updated>
            <content:encoded><![CDATA[<p>Try yourself and read the explanation.</p><figure><img alt="Most failed JavaScript interview questions." src="https://cdn-images-1.medium.com/max/1024/1*AQTVYeKTphXBndj11fOdrw.png" /></figure><p>True story — you don’t need to know JavaScript well to pass any JavaScript interview.</p><p>If you do interviews as a JavaScript developer from time to time, then you know that the questions in such interviews are always similar (more or less, okay!). Under different phrases, interviewers test you for knowledge of the same topics. And despite this, as you will see, the statistics of correct answers to such questions is quite low.</p><p>How to change the situation? Piece of cake — to do as many exercises as possible across these topics — and most importantly, to understand the result. Start with the ones we have selected for this article.</p><p>Below we give typical interview questions broken down by topic and the percentage of correct answers from our telegram channel. To give you more insight regarding these numbers, we should note that stats for other quizzes from our channel show a high level of JavaScript proficiency in our audience.</p><p>And now running to the questions.</p><h4>Event loop.</h4><p>It’s hard to imagine a JavaScript interview that doesn’t mention the event loop. And it’s not in vain. The theme is really fundamental and is used daily by every React, Angular, *substitute your framework* developer.</p><p><strong>Quiz №1. 18% of correct answers</strong></p><p>As an example, we have chosen a quiz that seems to cover all aspects of this topic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/768d7c57bd24e8a9a7d31a16eceddee7/href">https://medium.com/media/768d7c57bd24e8a9a7d31a16eceddee7/href</a></iframe><p><a href="https://t.me/intspirit/566">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>In the example, we see setTimeout, Promise, and some synchronous code.</p><p>The internal dialogue of a developer who answered this quiz correctly might look like this.</p><ul><li>Given zero delay, will the function we passed to setTimeout be called synchronously or asynchronously?</li><li>Despite the fact that the setTimeout function has zero delay, the callback function is called asynchronously. The engine will place the callback function in the <em>callback queue</em> (<em>macrotask</em> <em>queue</em>) and move it to the <em>call stack</em> when it is empty. Therefore, the number 1 will be skipped and number 2 will be displayed first in the console.</li><li>Will the function we passed as an argument to the Promise constructor be called synchronously or asynchronously?</li><li>The function that the Promise constructor takes as an argument is executed synchronously. Therefore, the next number to be displayed in the console is 3.</li><li>Given zero delay, will the function we passed as an argument to the promise’s then handler be called synchronously or asynchronously?</li><li>The callback in the then method is executed asynchronously, even though the promise resolves without delay. The difference with setTimeout is that the engine will place the promise callback in another queue — the <em>job queue</em> (<em>microtask queue</em>), where it will wait for its turn to be executed. Therefore, the next number that enters the console is 5.</li><li>What has more priority — <em>microtask</em> queue or <em>macrotask</em> queue or in other words — promises or setTimeout?</li><li><em>Microtasks</em> (promises) have a higher priority than <em>macrotasks</em> (setTimeout), so the next number in the console will be 4 and the last — 1.</li></ul><p>Analyzing the responses, we can conclude that the majority of respondents were mistaken in their assumption that the executor function, which was passed to the Promise constructor as an argument, is called asynchronously (44% voted for this option).</p><p>It was the simplest challenge that can be found in an interview on the Event Loop topic. In another blog post, we give examples of more complex challenges that even experienced seniors cannot cope with:</p><p><a href="https://intspirit.medium.com/understanding-the-browsers-event-loop-for-building-high-performance-web-applications-part-1-fe4b573a1520">Understanding the browser’s Event Loop for building high-performance web applications. Part 1.</a></p><h4>Context.</h4><p>Questions about context can catch up even experienced developers. For example, only 29% of developers solved this knotty but essentially simple task.</p><p><strong>Quiz №1. 29% of correct answers</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6fe5f2823668f4a32988cf7d1ea1955/href">https://medium.com/media/d6fe5f2823668f4a32988cf7d1ea1955/href</a></iframe><p><a href="https://t.me/intspirit/561">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>The value of this is set at the time the function is called.</p><p>In the example, the obj.foo function is passed as an argument to another callFoo function, which calls it without context.</p><p>In normal mode, when there is no execution context and the code is running in the browser environment, this refers to the window object, in strict mode it is undefined.</p><p>The correct answer is undefined.</p><p><strong>Quiz №2. 28% of correct answers</strong></p><p>Another common interview question is the value of this inside an arrow function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04bbdf229a9fd834b00067f77ccc74e5/href">https://medium.com/media/04bbdf229a9fd834b00067f77ccc74e5/href</a></iframe><p><a href="https://t.me/intspirit/488">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>Arrow functions don’t have their own this. Instead this inside an arrow function’s body points to the this value into the scope the arrow function is defined within.</p><p>Our function is defined in the global scope.</p><p>this in global scope refers to the global object (even in strict mode). Therefore the answer is 10.</p><h4>Arrow functions.</h4><p>An experienced interviewer (aka devil) might ask about arrow functions in a different context as well. For example, only 28% answered the following question.</p><p><strong>Quiz №1. 28% of correct answers</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f28049cce4dc92d8d4ac3a7d25b0ac4/href">https://medium.com/media/0f28049cce4dc92d8d4ac3a7d25b0ac4/href</a></iframe><p><a href="https://t.me/intspirit/492">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>Arrow functions do not have their own arguments object. Instead, the arguments is a reference to the arguments of the enclosing scope.</p><p>Therefore arguments[0] refers to the coef argument and the result of the quiz is 0.2.</p><p><strong>Quiz №2. 39% of correct answers</strong></p><p>Another question about arrow functions may look the following way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1993595650775f082aaada7020b69335/href">https://medium.com/media/1993595650775f082aaada7020b69335/href</a></iframe><p><a href="https://t.me/intspirit/490">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>Arrow functions cannot be used as constructors and will throw an error when called with new. They also do not have a prototype property:</p><p>TypeError: Cannot set properties of undefined (setting ‘getNum’)</p><p>Such questions are rare, but you should be ready for them. View more information about arrow functions on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">MDN</a>.</p><h4>Variable scope.</h4><p>A topic is worth exploring not only because of the popularity across the interviews, but also for practical reasons. If you understand variable scope well, you’ll save a lot of time from debugging code.</p><p>Let’s look at some common examples.</p><p><strong>Quiz №1. 38% of correct answers</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f3e87c15eb2a3bf722e5f669e089476/href">https://medium.com/media/8f3e87c15eb2a3bf722e5f669e089476/href</a></iframe><p><a href="https://t.me/intspirit/457">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>The place in the scope before the let / const variable’s definition is called a <em>temporary dead zone</em>.</p><p>If we try to access let / const variables before they are defined, a reference error will be thrown.</p><p>To easily remember how a language works, it’s helpful to understand why it works the way it does (so simple, ha?!).</p><p>This behavior was chosen because of the const variables. When accessing a var variable before it is defined, we get undefined. This would be unacceptable for const variables, because then it would not be a <em>constant</em>.</p><p>The behavior for let variables was done in an analogous way so that you can easily switch between these two types of variables.</p><p>Returning to our example.</p><p>Because the function call is above the definition of the bar variable, the variable is in a temporary dead zone.</p><p>The code throws an error:</p><p>ReferenceError: Cannot access ‘bar’ before initialization</p><p><strong>Quiz №2. 33% of correct answers</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e014a4675ac4725242f293db7f715d8/href">https://medium.com/media/7e014a4675ac4725242f293db7f715d8/href</a></iframe><p><a href="https://t.me/intspirit/365">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>In <em>named function expressions</em>, the name is local only to the function body and is not available from outside. So foo doesn’t exist in the global scope.</p><p>The typeof operator returns undefined for not defined variables.</p><p><strong>Quiz №3. 36% of correct answers</strong></p><p>The following example is not recommended for use in real life, but you should know how this code will work at least in order to satisfy the interest of the interviewer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/648cb31ec20db06c97b7fb213e522626/href">https://medium.com/media/648cb31ec20db06c97b7fb213e522626/href</a></iframe><p><a href="https://t.me/intspirit/352">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>For a function that has <em>complex</em> parameters (destructuring, default values), the list of parameters is enclosed in its own scope.</p><p>Therefore, creating the bar variable in the function body does not affect the variable of the same name in the parameter list, and the getBar() function gets bar from its parameters via a closure.</p><p>Generally speaking, we have noticed despite the fact that ES6 has been released for more than 7 years ago, its features remain poorly understood by developers. Of course, everyone knows the syntax of features in this release, but only a few understand it deeper.</p><p>Don’t miss our next article on ES6 features.</p><h4>ES6 modules.</h4><p>If you are an interviewer and for some reason you don’t like the candidate, the modules will definitely help you to fail anybody.</p><p>For the purposes of this article, we have chosen one of the easiest tasks on this topic. But trust us, ES6 modules are way more complex.</p><p>We have collected 13 quizzes on the topic of modules that cover all the most complex and little-known aspects of this topic. If you can correctly answer (and explain your answer to) at least half of these quizzes, you are already a superhero. Check yourself:</p><p><a href="https://javascript.plainenglish.io/50-shades-of-es6-modules-95cd0b016156">50 shades of ES6 modules</a></p><p><strong>Quiz №1. 41% of correct answers</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5acb49a4d57e19a1a064f32badd82f96/href">https://medium.com/media/5acb49a4d57e19a1a064f32badd82f96/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/756a5a9c01460d7c91f610c0c9754796/href">https://medium.com/media/756a5a9c01460d7c91f610c0c9754796/href</a></iframe><p><a href="https://t.me/intspirit/447">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>Imports are <em>hoisted</em>.</p><p><em>Hoisting</em> is a mechanism in JS where variables and function declarations are moved to the top of their scope before the code is executed.</p><p>All dependencies will be loaded before the code runs.</p><p>So, the answer is: helper.js index.js 3</p><h4>Hoisting.</h4><p>Another popular interview topic is hoisting.</p><p><strong>Quiz №1. 40% of correct answers</strong></p><p>Despite the fact that the chosen quiz is out of touch with reality, it perfectly explains the mechanism of hoisting. If you understand how this code works, you shouldn’t have any problems with almost all other hoisting questions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95304506111aa664289d61aaff43f9cb/href">https://medium.com/media/95304506111aa664289d61aaff43f9cb/href</a></iframe><p><a href="https://t.me/intspirit/559">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>Function and variable declarations are placed at the top of their scope, and the initialization of variables occurs at the time of script execution.</p><p>Repeated declarations of a variable with the same name are skipped.</p><p>Functions are always hoisted first. In whatever order the declarations of a function and a variable with the same name occur in your code, the function takes precedence, because it rises higher.</p><p><strong>Example 1.</strong></p><p>function num() {}<br> var num;<br> console.log(typeof num); // function</p><p><strong>Example 2.</strong></p><p>var num;<br> function num() {}<br> console.log(typeof num); // function</p><p>Variables are always initialized at the very end.</p><p>var num = 8;<br> function num() {}</p><p>will be transformed into:</p><p>function num() {}<br> var num; // repeated declaration is ignored<br> num = 8;</p><p>As a result, num = 8.</p><p><strong>Quiz №2. 12% of correct answers</strong></p><p>Do you remember we said that modules are hard? Modules plus hosting can blow the mind of any programmer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e115f7161b7d7f972d12be29db879792/href">https://medium.com/media/e115f7161b7d7f972d12be29db879792/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/756603359d2b7e6aef84a64fbf905649/href">https://medium.com/media/756603359d2b7e6aef84a64fbf905649/href</a></iframe><p><a href="https://t.me/intspirit/463">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>export default function foo() {}</p><p>is equal to</p><p>function foo() {}<br> export { foo as default }</p><p>And it’s time to remember that functions are hoisted and variable initialization always happens after the function/variable declaration.</p><p>After the engine is processed the module code you can imagine it in the following form:</p><p>function foo() {}<br> foo = 25;<br> export { foo as default }</p><p>So the correct answer is number.</p><h4>Promises</h4><p>Surprisingly, programmers know the topic of promises better than they think. Interview questions on this topic are usually the most fundamental and most part can handle them. But we still could not bypass it, because neither do the interviewers.</p><p><strong>Quiz №1. 46% of correct answers</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c09662a869b1ef7eb073ec482f231c81/href">https://medium.com/media/c09662a869b1ef7eb073ec482f231c81/href</a></iframe><p><a href="https://t.me/intspirit/569">Try yourself</a> and read the explanation.</p><p><strong>Explanation.</strong></p><p>Let’s see how this code will be executed step by step.</p><p>1. The first then handler throws an error (means — returns rejected promise).</p><p>2. The next then handler does not fire because an error was thrown, instead execution moves on to the next catch.</p><p>3. The catch handler prints an error and returns an empty promise. The catch handler, like the then handler, always returns a promise.</p><p>4. Because the catch handler returned a promise, the next then handler is called and returns a promise with a value of 2.</p><p>5. The last then handler is called and prints 2.</p><p><strong>In conclusion.</strong></p><p>As always, we want to encourage you to keep learning the language you write every day and <strong>let’s make IT better</strong>!</p><blockquote><em>Subscribe to the </em><a href="https://t.me/intspirit">telegram-channel</a><em> to easily pass any JavaScript interview.</em></blockquote><blockquote><em>Follow us on </em><a href="https://intspirit.medium.com/">Medium</a><em> to not miss new stuff.</em></blockquote><blockquote><em>Pop into our </em><a href="https://www.linkedin.com/company/intspirit">LinkedIn</a><em> for other cool things we do.</em></blockquote><p>Share in comments — what was your most difficult JavaScript interview question?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=849664e5bee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[50 shades of ES6 modules]]></title>
            <link>https://javascript.plainenglish.io/50-shades-of-es6-modules-95cd0b016156?source=rss-5e5426eda6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/95cd0b016156</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Intspirit Ltd]]></dc:creator>
            <pubDate>Fri, 09 Dec 2022 09:56:01 GMT</pubDate>
            <atom:updated>2022-12-09T09:56:01.415Z</atom:updated>
            <content:encoded><![CDATA[<h4>The toughest challenges of the hardest JavaScript topic for developers.</h4><figure><img alt="JS: 50 shade of ES6 Modules." src="https://cdn-images-1.medium.com/max/1024/1*ahrhFHocDpxTHdFfRqsUag.png" /></figure><p>If you ask a developer: “What is the hardest JS topic for you?”, you will never hear that it’s ES6 modules. But statistics know better! We counted the number of incorrect answers to quizzes in our telegram channel across various topics and found out that the ES6 modules is the one of anti-leaders. Other TOP-5 toughest topics for developers can be viewed <a href="https://medium.com/@intspirit/top-of-js-topics-mostly-failed-by-developers-53397f13eb78">here</a>.</p><p>It seems like many developers think that ES6 modules are no more than <em>export — import</em> keywords. In fact, it’s much more diverse. It has powerful features and slippery pitfalls that few developers know about. In this article we will look at all of them, using the quizzes of our telegram channel as examples. This time, we will not rank the tasks in the top by the number of correct answers, since the explanations for some tasks may be based on the previous ones, however, for more interest, we will indicate the percentage of developers who answered the quiz correctly. Go!</p><h4>Quiz #1. 53% of correct answers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11283626bc2f6723c0484ce02fe22846/href">https://medium.com/media/11283626bc2f6723c0484ce02fe22846/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c62e09b0a51bf5c0b724fa9d0771f5f8/href">https://medium.com/media/c62e09b0a51bf5c0b724fa9d0771f5f8/href</a></iframe><p><a href="https://t.me/intspirit/461">Try yourself</a></p><p>First, let’s remember all the variety of import and export syntax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7Vh6K-REoI-ni3PiZ4jLA.png" /><figcaption>Export syntax</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UubIE6RFvgPUOiaMQ2I13g.png" /><figcaption>Import syntax</figcaption></figure><p>If you check the table with Import syntax, you will see that there is no syntax matching our code:</p><p>import { default } from ‘./module.mjs’;</p><p>Because this syntax is forbidden. The quiz code throws the following error:</p><p><em>SyntaxError: Unexpected reserved word</em></p><p>In the line import { default } from ‘./module.mjs’; the default is the name of export and the name of a variable in this scope, which is prohibited because default is a reserved word. The fix is quite easy:</p><p>import { default as foo } from ‘./module.mjs’;</p><p>Now, default is the name of export and foo is the name of a variable. In the other words, if you want to use a named import syntax for the default export you must rename it. That’s it, so simple!</p><h4><strong>Quiz #2. 35% of correct answers</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf6034ade5acb5199d99582a0a466c4f/href">https://medium.com/media/cf6034ade5acb5199d99582a0a466c4f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31d79805d6f9ff7113162ea04a609129/href">https://medium.com/media/31d79805d6f9ff7113162ea04a609129/href</a></iframe><p><a href="https://t.me/intspirit/447">Try yourself</a></p><p>The important nuance that not many developers knew about is that imports are hoisted. That is, they go up while the engine is parsing the code. All dependencies will be loaded before the code runs.</p><p>That is why we will see logs in the following order:</p><p>helper.js, index.js, 3</p><p>If you want some code to be executed before an import declaration, consider moving it to a separate file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e18c6a19834c17fd886c4066d206187e/href">https://medium.com/media/e18c6a19834c17fd886c4066d206187e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66766a789db6dec352d6aa2c5aab7b9a/href">https://medium.com/media/66766a789db6dec352d6aa2c5aab7b9a/href</a></iframe><p>We have the expected output now:</p><p>index.js, helper.js, 3</p><h4>Quiz #3. 42% of correct answers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d43a095b9301ed3d11eccbd9a27fea25/href">https://medium.com/media/d43a095b9301ed3d11eccbd9a27fea25/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1c31ae68375e6946275558ea1f2ea00/href">https://medium.com/media/e1c31ae68375e6946275558ea1f2ea00/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/542dbf75cec7ef188cfc438866b5a554/href">https://medium.com/media/542dbf75cec7ef188cfc438866b5a554/href</a></iframe><p><a href="https://t.me/intspirit/459">Try yourself</a></p><p>Modules are <em>singletons</em>.</p><p>No matter how many times you import a module from the same location or from different places, the module will only be executed and loaded once. In the other words, there is only one module instance.</p><figure><img alt="A cat with a thinking face and inscription: Interesting. Tell me more." src="https://cdn-images-1.medium.com/max/500/1*8pDv7TVmWP4p2_viyxB2yg.jpeg" /><figcaption>Creds: <a href="https://imgflip.com/i/3mol6q">https://imgflip.com/i/3mol6q</a></figcaption></figure><h4>Quiz #4. 34% of correct answers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2a5df3566b5166974a12eaf0d6d05cf/href">https://medium.com/media/a2a5df3566b5166974a12eaf0d6d05cf/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d85def7b23935a7cb6f0c9f27ebd5151/href">https://medium.com/media/d85def7b23935a7cb6f0c9f27ebd5151/href</a></iframe><p><a href="https://t.me/intspirit/412">Try yourself</a></p><p>In the comments to our previous <a href="https://medium.com/@intspirit/only-10-of-developers-can-solve-these-javascript-challenges-f4804c7c54eb">article</a>, in which we collected the most difficult quizzes from our channel, some wrote that they did not consider it necessary to know the language so thoroughly. Well, disagree. We believe the more you know, the more efficient you are (ceteris paribus). This statement has been repeatedly proven in practice in our company.</p><p>Perhaps this feature is one of those that will be written about — “why do we need to know this.” And it’s really unlikely that you will use it every day. But, one day, it will come in handy and how wonderful it is to save time that you would have spent on Google.</p><p>So according to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta">MDN</a>:</p><blockquote>The import.meta object exposes context-specific metadata to a JavaScript module. It contains information about the module.</blockquote><blockquote>It returns an object with a url property indicating the base URL of the module. This will either be the URL from which the script was obtained, for external scripts, or the document base URL of the containing document, for inline scripts.</blockquote><p>Note that this will include query parameters and/or hash (i.e., following the ? or #).</p><h4>Quiz #5. 45% of correct answers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c6c0db91a95d0e37f1bd12abb327998/href">https://medium.com/media/2c6c0db91a95d0e37f1bd12abb327998/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b18b52ef058959f4ba4d6f4fcded10a/href">https://medium.com/media/3b18b52ef058959f4ba4d6f4fcded10a/href</a></iframe><p><a href="https://t.me/intspirit/449">Try yourself</a></p><p>Another extremely important moment that most developers miss is that imported variables behave like <em>constants</em> in the scope of the importing module.</p><p>To make the code work, you can export, for example, an object and change its property.</p><h4>Quiz #6. 11% of correct answers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f29dbe9bf5a8cdfba22692c1278cf40e/href">https://medium.com/media/f29dbe9bf5a8cdfba22692c1278cf40e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ea0fb63936ef2c468d403a9c66bc0c4/href">https://medium.com/media/1ea0fb63936ef2c468d403a9c66bc0c4/href</a></iframe><p><a href="https://t.me/intspirit/463">Try yourself</a></p><p>This quiz seems to have the lowest number of correct answers. On the one hand, this is expected, because this is a corner case. On the other hand, if you stay focused a little bit more, you’ll see that the task is actually based on fundamental things everyone should know (and probably knows, just failed to recognize them).</p><p>First of all, this</p><p>export default function foo() {}</p><p>is equal to</p><p>function foo() {}<br> export { foo as default }</p><p>and we would like to say that this is also equal to</p><p>function foo() {}<br> export default foo</p><p>but it’s not.. Don’t be surprised, just keep reading. We will return to this in the next quiz.</p><p>And now it’s time to remember that functions are hoisted and initialization of a variable always goes after a function/variable declaration. Isn’t that the foundation of the foundations?</p><p>After the engine has processed the module code, it looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3420c2c65ee694969656a2bdd31ad47/href">https://medium.com/media/a3420c2c65ee694969656a2bdd31ad47/href</a></iframe><p>Thus, the quiz result is the number.</p><h4>Quiz #7. 17% of correct answers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/951237f781c59d22485b90a7fdd0ee78/href">https://medium.com/media/951237f781c59d22485b90a7fdd0ee78/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72ed9702b7897b271a41d61fa0457810/href">https://medium.com/media/72ed9702b7897b271a41d61fa0457810/href</a></iframe><p><a href="https://t.me/intspirit/465">Try yourself</a></p><p>In most cases, the import data is <em>live</em>. That is, if the exported value has changed, this change is reflected in the imported variable.</p><p>But this is not true for the default export:</p><p>export default foo;</p><p>When you use this syntax, you are not exporting a variable, but its value. You can export default values ​​without using variables at all like this:</p><p>export default ‘hello’;<br>export default 42;</p><p>If you look at the table with the export syntax from Quiz #1, you will see that the export default function () {} is in a different column (Default export) than the export default foo (Export of values).</p><p>This is because they behave differently, functions are still passed as live references:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6adff288f8223a90b3d12daaa0870246/href">https://medium.com/media/6adff288f8223a90b3d12daaa0870246/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/511587c258e217d8daad913acb46b08b/href">https://medium.com/media/511587c258e217d8daad913acb46b08b/href</a></iframe><p>Let’s look at the exports table once again.</p><p>export { foo as default }; is in the Named Export column, which is different from both. But for us, the only important thing is that it is not in the Export of values column. So this means when you export data this way, it will be a live binding to the imported value.</p><h4>Quiz #8. 40% of correct answers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdf6442530752ccc567f8b795bbf9305/href">https://medium.com/media/bdf6442530752ccc567f8b795bbf9305/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30129dd14cb738240b3b7330947150b5/href">https://medium.com/media/30129dd14cb738240b3b7330947150b5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44820ee000493db80433590f47690deb/href">https://medium.com/media/44820ee000493db80433590f47690deb/href</a></iframe><p><a href="https://t.me/intspirit/406">Try yourself</a></p><p>The line import { num } from ‘./module2.mjs’; will throw an error because the import construction must be at the top-level of the script:</p><p><em>SyntaxError: Unexpected token ‘{‘</em></p><p>This is an important limitation, which, together with the restriction to use variables in file paths, makes ES6 modules to be <em>static</em>. This means that you don’t have to execute a code to find out all the dependencies between modules unlike Common.js modules that are used in Node.js.</p><p>In this example, which uses Common.js modules, to figure out which module a or b will be loaded, the following code needs to be run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7a03e765817e84ff16bf444131a7399/href">https://medium.com/media/e7a03e765817e84ff16bf444131a7399/href</a></iframe><p>The static nature of modules has a lot of benefits. Here are some of them:</p><ol><li>You always know the exact structure of imported data. This helps linters to find typos before executing the code.</li><li>Asynchronous loading. It’s because modules are static, you can load imports before executing the module body.</li><li>Support for circular dependencies. We will explore this possibility in more details in the next quiz.</li><li>Efficient bundling. Not to talk much this topic, you can see on your own how the <a href="https://rollupjs.org/guide/en/">Rollup</a> bundler can effectively build ES6 modules in <a href="https://blog.developer.adobe.com/optimizing-javascript-through-scope-hoisting-2259ef7f5994">this article</a>.</li></ol><p>In ES6 if you need to load a module conditionally, you can use the import() function-like construction, which will be highlighted in the next quizzes.</p><h4>Quiz #9. 33% of correct answers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57cb1bc0b4b67bde3a04d6de4f277878/href">https://medium.com/media/57cb1bc0b4b67bde3a04d6de4f277878/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62c0e0b9b02a90337272280b56e925db/href">https://medium.com/media/62c0e0b9b02a90337272280b56e925db/href</a></iframe><p><a href="https://t.me/intspirit/467">Try yourself</a></p><p>In the code above, we can see the circular dependencies: index.mjs imports the double and square functions from module.mjs, while module.mjs imports the calculation function from index.mjs.</p><p>This code works because ES6 modules, by their nature, support circular dependencies pretty well. For example, if we rewrite this code to use Common.js modules, it will no work anymore:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/561cf60e9879cce806ab989d098641bf/href">https://medium.com/media/561cf60e9879cce806ab989d098641bf/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0c3a41b7f1957c6aae6a08828e4029e/href">https://medium.com/media/c0c3a41b7f1957c6aae6a08828e4029e/href</a></iframe><p>This is a common “pain” in Node.js. Let’s see how this code actually works:</p><ol><li>index.js starts loading</li><li>loading is interrupted on the first line to load module.js:</li></ol><p>const helpers = require(‘./module.js’);</p><p>3. module.js starts loading</p><p>4. on the line console.log(actions.calculate(3)); the code throws an error because actions.calculate is not defined. This is because Common.js loads modules synchronously. index.js has not loaded yet and it’s export object is currently empty.</p><p>If you call an imported function with a delay, the index.js module will have time to load and code will work accordingly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce25525ea76da0c2035190cfea36554e/href">https://medium.com/media/ce25525ea76da0c2035190cfea36554e/href</a></iframe><p>As you know from the previous quiz, ES6 modules support circular dependencies because they are static — the module’s dependencies are loaded before the code is executed.</p><p>Another thing that makes the above code work is hoisting. When the calculate function is called, we have not yet been on the line with its definition.</p><p>Here is how the code looks like after bundling the modules:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6ce23e787008f9bf6913c6faae02302/href">https://medium.com/media/c6ce23e787008f9bf6913c6faae02302/href</a></iframe><p>It won’t work without hoisting.</p><p>If we change the calculation declaration function to a function expression:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5411135f978186fc4882c023baa2a33b/href">https://medium.com/media/5411135f978186fc4882c023baa2a33b/href</a></iframe><p>it will throw the following error:</p><p><em>ReferenceError: Cannot access ‘calculate’ before initialization</em></p><h4><strong>Quiz #10. 31% of correct answers</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebf5862e990d7ac0bef6c02f057082a6/href">https://medium.com/media/ebf5862e990d7ac0bef6c02f057082a6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec929f459d57107116da64f71fea1e6e/href">https://medium.com/media/ec929f459d57107116da64f71fea1e6e/href</a></iframe><p><a href="https://t.me/intspirit/404">Try yourself</a></p><p><em>Top-level await</em> is a super useful feature that many developers don’t know about, perhaps due to the fact that it was introduced very recently, in ECMAScript 2022. Ah, that’s nice!</p><figure><img alt="Nice." src="https://cdn-images-1.medium.com/max/512/1*LouJosfcctd3i_5dPKQnOQ.png" /></figure><p>According to <a href="https://github.com/tc39/proposal-top-level-await">tc39 top-level await proposal</a>:</p><blockquote>Top-level await enables modules to act as big async functions: With top-level await, ECMAScript Modules (ESM) can await resources, causing other modules who import them to wait before they start evaluating their body.</blockquote><p>The standard behavior of modules is that the code in a module is not executed until all modules it imports are loaded and their code is executed (look at Quiz #2). In fact, with the advent of top-level await, nothing changes. The code in a module is not executed until all the code in the imported modules has been executed, only now this includes waiting for all the awaited promises in the module to be resolved.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bae21e4eafb9ebc8144e262a3d05ee1/href">https://medium.com/media/6bae21e4eafb9ebc8144e262a3d05ee1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5235533e7866dfe254f6dd4193af873b/href">https://medium.com/media/5235533e7866dfe254f6dd4193af873b/href</a></iframe><p>Output:</p><p>module.js<br>module.js: promise 1<br>module.js: promise 2<br>index.js<br>num = 20</p><p>If we remove awaits from lines 5 and 13 in module.js, and add timeouts in the file index.js like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b56d0a2f5829ea0eec3356e9268f35d5/href">https://medium.com/media/b56d0a2f5829ea0eec3356e9268f35d5/href</a></iframe><p>the output will be:</p><p>module.js<br>index.js<br>num = 5<br>module.js: promise 1<br>timeout num = 10<br>module.js: promise 2<br>timeout num = 20</p><p>We will return to the top-level await feature in future quizzes.</p><h4><strong>Quiz #11. 16% of correct answers</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35cf3deb5bdafa9def53a696c7c76d5f/href">https://medium.com/media/35cf3deb5bdafa9def53a696c7c76d5f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d5daa895832a7e7a4f8e8768ddcada9/href">https://medium.com/media/7d5daa895832a7e7a4f8e8768ddcada9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4e7db02ba5a0fe78e9b5cc7ee32c398/href">https://medium.com/media/d4e7db02ba5a0fe78e9b5cc7ee32c398/href</a></iframe><p><a href="https://t.me/intspirit/408">Try yourself</a></p><p>According to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import">MDN</a>:</p><blockquote>The import() call, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically. It allows one to circumvent the syntactic rigidity of import declarations and load a module conditionally or on demand.</blockquote><p>This feature was introduced in ES2020.</p><p>import(module) returns a promise which fulfills to an object containing all exports from the module.</p><p>Since import(module) returns a promise, in order to fix the quiz code we must add await keyword before the import call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/361d48ca15655010d0f5eed44450a253/href">https://medium.com/media/361d48ca15655010d0f5eed44450a253/href</a></iframe><p>Here we again use the top-level await, which reminds us of the coolness of this feature.</p><p>I’m sure at least once your application crashed with an error:</p><p><em>SyntaxError: await is only valid in async functions</em></p><p>This often happens when trying to call an asynchronous function from the global scope. To solve this problem, we had to dodge ugly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67cbae9974858d4ff04bba500ebe3af7/href">https://medium.com/media/67cbae9974858d4ff04bba500ebe3af7/href</a></iframe><p>This is not only ugly but may cause an error in case of using this pattern for loading modules asynchronously. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/895a629e692bd1cab7233bfaf7bc2890/href">https://medium.com/media/895a629e692bd1cab7233bfaf7bc2890/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/419a0c6b948288cd9cb331d52dc9a890/href">https://medium.com/media/419a0c6b948288cd9cb331d52dc9a890/href</a></iframe><p>When importing module1.mjs what will be the result of num — the value from the module2 or undefined? It will depend on when the variable will be accessed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94baec2527d848d02e689c7e203a81a3/href">https://medium.com/media/94baec2527d848d02e689c7e203a81a3/href</a></iframe><p>With a top-level await whenever you access num imported from module1, it will never be undefined:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ade47dde431c5b31267f3f1a01966a73/href">https://medium.com/media/ade47dde431c5b31267f3f1a01966a73/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/984fc299e084431eb7783c4dd78a7b50/href">https://medium.com/media/984fc299e084431eb7783c4dd78a7b50/href</a></iframe><h4><strong>Quiz #12. 21% of correct answers</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dba66b33963a83be903470fad6d812bf/href">https://medium.com/media/dba66b33963a83be903470fad6d812bf/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eccc58e4be8fe31fe83c3642f92448b/href">https://medium.com/media/9eccc58e4be8fe31fe83c3642f92448b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4cbea87a7a89e282538b912b637b29b/href">https://medium.com/media/a4cbea87a7a89e282538b912b637b29b/href</a></iframe><p><a href="https://t.me/intspirit/410">Try yourself</a></p><p>The above code will throw an error:</p><p><em>TypeError: Cannot convert object to primitive value</em></p><p>Agree, a rather unexpected error wording. Let’s figure out where this error comes from.</p><p>In this piece of code, we use a dynamic import which we have already met in the previous example. To understand the problem in this code, we need to take a closer look at the return value of import().</p><p>The values ​​of the variables module1 and module2 are not what we’ve expected. import() returns a promise which fulfills to an object with the same shape as a namespace import:</p><p>import * as name from moduleName</p><p>The default export available as a key named default.</p><p>So instead of the values ​​1 and 2, we have objects { default: 1 } and { default: 2 } ​​in the variables module1 and module2 respectively.</p><p>Well, why do we get such a strange error when multiplying two objects, and not NaN as we are used to?</p><p>This is because the returned object has a null prototype. Therefore, it does not have a toString() method, which is used to convert objects to primitives. If this object had an Object prototype, we would see NaN in the console.</p><p>To fix the quiz code, we need to make the following changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/205a2805c2b35b06e618daa972c1ae1c/href">https://medium.com/media/205a2805c2b35b06e618daa972c1ae1c/href</a></iframe><p>or</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0064cce91c363032998e4040b9361b91/href">https://medium.com/media/0064cce91c363032998e4040b9361b91/href</a></iframe><p>To read more about import(): <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import">MDN</a>.</p><h4><strong>Quiz #13. 17% of correct answers</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1e2dccf7c004609fd62d23b5cd241a5/href">https://medium.com/media/c1e2dccf7c004609fd62d23b5cd241a5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b2cdccbd6ef9adc5daaba25cf49563d/href">https://medium.com/media/7b2cdccbd6ef9adc5daaba25cf49563d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a36af5adaaaf7c7cc3f16e585089bfe0/href">https://medium.com/media/a36af5adaaaf7c7cc3f16e585089bfe0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcb9610b86be6f73b3bd478452081573/href">https://medium.com/media/dcb9610b86be6f73b3bd478452081573/href</a></iframe><p><a href="https://t.me/intspirit/380">Try yourself</a></p><p>The export * from ‘module’ syntax re-exports all named exports from <em>‘module’ </em>file as the named exports of the current file. If there are several exports with the <strong>same</strong> name, neither one is re-exported.</p><p>So running this code we would see undefined in the console. Only 17% of responders answered this quiz correctly and the majority of responders (59%) thought this code would throw an error. And indeed this silently failing seems not typically for strict mode. (As we remember JavaScript modules are automatically in strict mode.) Let me know in the comments if you know the reason for this behavior.</p><p>By the way, if in the same situation we <em>explicitly</em> import x, we would have an error as expected:</p><p>import { x } from ‘./intermediate.js’;</p><p><em>SyntaxError: The requested module ‘./intermediate.js’ contains conflicting star exports for name ‘x’</em></p><h4><strong>In conclusion.</strong></h4><p>As always, we want to encourage you to keep learning the language you write every day and <strong>let’s make IT better</strong>!</p><blockquote><em>Subscribe to the </em><a href="https://t.me/intspirit">telegram-channel</a><em> to become the “know-it-all” person in the office.</em></blockquote><blockquote><em>Follow us on </em><a href="https://intspirit.medium.com/">Medium</a><em> to not miss new stuff.</em></blockquote><blockquote><em>Follow us on </em><a href="https://www.linkedin.com/company/intspirit">LinkedIn</a><em> for other cool things we do.</em></blockquote><p>Share in the comments — in which topic in JavaScript do you think you understand the worst? Perhaps next time we will devote an article to this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95cd0b016156" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/50-shades-of-es6-modules-95cd0b016156">50 shades of ES6 modules</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Only 10% of developers can solve these JavaScript challenges]]></title>
            <link>https://intspirit.medium.com/only-10-of-developers-can-solve-these-javascript-challenges-f4804c7c54eb?source=rss-5e5426eda6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4804c7c54eb</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Intspirit Ltd]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 12:56:01 GMT</pubDate>
            <atom:updated>2022-09-13T11:26:41.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Text: TOP-5 most failed JS Challenges based on quizzes statistics. By Intspirit." src="https://cdn-images-1.medium.com/max/1024/0*I-U-2PFfLuRGfQrK" /><figcaption>TOP-5 most failed JS Challenges.</figcaption></figure><p>Some time ago we created a telegram-channel with JS quizzes &amp; explanations. Today, we’d like to share TOP-5 JS challenges that were the hardest ones for developers. This TOP-5 is based on the percentage of failed answers to hundreds of the published quizzes.</p><h3>Intro</h3><p>We have already posted an article with the hardest <strong>topics</strong> based on the statistics of answers to these quizzes. To identify such topics we divided all published quizzes by topic (15 topics in total) and calculated the average percentage in each topic.</p><p>The most interesting thing about this experiment was that in addition to counting the correct answers, we conducted a survey on the most difficult aspects of Javascript and the results were very different. In the survey, the majority of respondents answered that the most difficult topic for them is <em>Promises</em>, while according to statistics, Promises took only the 4th place. You may find all the results here:</p><p><a href="https://intspirit.medium.com/top-of-js-topics-mostly-failed-by-developers-53397f13eb78">Top of JS Topics mostly failed by developers</a></p><p>We should leave a note about the percentage of correct answers that you will see next to each task. You should not take this note as something constant and 100% reflecting reality. Firstly, new programmers answer our published quizzes every day and change statistics. All numbers presented in the article were fixed at the time of publication of the article. Secondly, some answers, of course, are accidentally guessed or clicked in the wrong place, etc. Nevertheless, having interviewed a huge number of JS developers, we can say with confidence that this statistics clearly reflects reality.</p><figure><img alt="Guy underwater. Text: programming PRO tip: code JavaScript underwater, so nobody could see you crying." src="https://cdn-images-1.medium.com/max/600/1*Lsn_-6TyPI7pTvKirj2mqg.jpeg" /><figcaption>Briefly about quizzes in the article. Credit: <a href="https://starecat.com/programming-pro-tip-code-javascript-underwater-so-nobody-could-see-you-crying/">https://starecat.com/programming-pro-tip-code-javascript-underwater-so-nobody-could-see-you-crying/</a></figcaption></figure><p>So let’s look at the <strong>TOP-5 most difficult JS challenges</strong> and analyze them. Spoiler: only 8% of responders solved the TOP-1 quiz correctly.</p><h3>TOP-5. Default function parameters &amp; function <em>length</em> property. <em>18%</em> of correct answers.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efd7e25528e7a86d5264d2066ff542a5/href">https://medium.com/media/efd7e25528e7a86d5264d2066ff542a5/href</a></iframe><p><a href="https://t.me/intspirit/329">Try yourself</a></p><p>The key point here is that the <em>length</em> property of a function is supposed to provide an info about the <em>arity</em> of a function, which is calculated as a number of her <em>formal</em> defined parameters.</p><p>Default parameters feature was introduced in <a href="https://262.ecma-international.org/6.0/">ES2015</a>. Before that all function parameters were considered as <em>formal</em> parameters and function length property was used to return <em>all</em> function parameters number.</p><p>With the introduction of default parameters, the behavior of the length property has changed. Since it is obvious that a parameter with a default value is <em>optional</em>, such a parameter is not included in the length of the function. According to common sense, all parameters following the parameter with a default value are also optional. Therefore, they are also not included in the length property of the function.</p><h3>TOP-4. <em>Object.defineProperty</em> method and its default parameters. <em>14%</em> of correct answers.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/522b327593033ea293b8bb2a43af0736/href">https://medium.com/media/522b327593033ea293b8bb2a43af0736/href</a></iframe><p>Most of the respondents answered undefined to this quiz. Reason: not knowing how the <em>Object.defineProperty()</em> method works.</p><p>The method <em>Object.defineProperty()</em> defines a new property on an object, or modifies an existing property on an object.</p><p>Syntax:</p><blockquote>Object.defineProperty(obj, prop, descriptors)</blockquote><p>Where:</p><blockquote>obj<em> — the object on which to define or modify the property.</em></blockquote><blockquote>prop<em> — the name of the property to be defined or modified.</em></blockquote><blockquote>descriptors<em> — descriptors for the property.</em></blockquote><p>Property descriptors are a set of flags that configure that property.</p><p>There are two types of descriptors: data<em> </em>descriptors<em> </em>(value, writable, enumerable, configurable)<em> </em>and access<em> </em>descriptors (get and set). In the context of this example, we are interested in<em> </em>data descriptors.</p><p>By default, properties added using <em>Object.defineProperty() </em>are <strong>not writable, not enumerable, </strong>and<strong> not configurable.</strong></p><p>The <em>configurable</em> attribute specifies whether the property can be removed from the object, and whether the property descriptor can be changed in the future. If true, then the property will be available for deletion and modification of its descriptor, if false, then no. The default will be set to <em>false</em>.</p><p>Therefore, the correct answer to the quiz is intspirit. An attempt to delete the property will be ignored. And if you run the code in strict mode, you will get an error:</p><blockquote>TypeError: Cannot delete property ‘myCompany’ of #&lt;Object&gt;</blockquote><h3>TOP-3. <em>Array.map</em> &amp; <em>parseInt</em>. <em>14%</em> of correct answers.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a911afb1b9cc3fbaff6cf82bec5bd536/href">https://medium.com/media/a911afb1b9cc3fbaff6cf82bec5bd536/href</a></iframe><p><a href="https://t.me/intspirit/217">Try yourself</a></p><p>A task of mindfulness. The <em>Array.map()</em> method accepts a callback function that takes 3 parameters. We will only be interested in the first two: value and index. The <em>parseInt</em> function takes 2 parameters: a string to convert to a number and a radix.</p><p>So in our case parseInt would be called with following arguments:</p><p>parseInt(‘9’, 0); <em><br></em>parseInt(‘10’, 1);<em><br></em>parseInt(‘11’, 2);</p><p>To understand how parseInt will work with those radixes, let’s take a look at radix parameter description at <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt">mdn</a>:</p><blockquote>radix — <em>an integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. If outside this range, the function will always return </em>NaN<em>. If 0 or not provided, JavaScript assumes the following:</em></blockquote><blockquote><em>1. If the input string, with leading whitespace and possible +/- signs removed, begins with 0x or 0X (a zero, followed by lowercase or uppercase X), radix is assumed to be </em>16<em> and the rest of the string is parsed as a hexadecimal number.</em></blockquote><blockquote><em>2. If the input string begins with any other value, the radix is </em>10<em> (decimal).</em></blockquote><p>According to this definition, we get the following results:</p><ol><li>parseInt(‘9’, 0)<em> </em>-&gt; radix 0 equates to a call without radix. Because first argument does not start with <em>0x</em> or <em>0X</em>, radix will default to <br>10 -&gt; parseInt(‘9’, 10)<em> </em>-&gt; 9</li><li>parseInt(‘10’, 1)-&gt; 1 — invalid radix (out of range) -&gt; NaN</li><li>parseInt(‘11’, 2) -&gt; 2 — valid radix, 11 in binary is 3 -&gt; 3</li></ol><h3>TOP-2. Cloning an object using <em>Object.create</em> and <em>Object.assign</em>. <em>11%</em> of correct answers.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3028fc8de43c29336b80b996d6d40205/href">https://medium.com/media/3028fc8de43c29336b80b996d6d40205/href</a></iframe><p><a href="https://t.me/intspirit/339">Try yourself</a></p><p>There was a series of quizzes in our <a href="https://t.me/intspirit">channel</a>, dedicated to the differences in the work of <em>Object.assign</em> and <em>…spread</em> operator. For anyone interested in deep JS, we strongly recommend that you solve all of them. Under each quiz you will find a detailed description of how it all works. This is just a brief description of how the code in this example works, as it proved to be the most difficult for the respondents in the entire quiz series.</p><p>So.. let’s understand what happens in this example.</p><p>1. A User constructor-function with the verified property set to true and its instance are created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ee055329a9b9f42fb9efdf99add07e1/href">https://medium.com/media/5ee055329a9b9f42fb9efdf99add07e1/href</a></iframe><p>2. An admin object is created using the user object as a prototype. According to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create">mdn</a>:</p><blockquote><em>The </em>Object.create() <em>method creates a new object, using an existing object as the prototype of the newly created object.</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afd58897b9fe30be02116382f8070387/href">https://medium.com/media/afd58897b9fe30be02116382f8070387/href</a></iframe><p>3. Two clones are created: one using the <em>…spread</em> operator, the other using <em>Object.assign</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58d2aced28ab4b42bb2d0e49c788f0b4/href">https://medium.com/media/58d2aced28ab4b42bb2d0e49c788f0b4/href</a></iframe><blockquote><em>Do you know the difference between </em>rest<em> and </em>spread<em> operators? Both use three dots … but these two operators are not the same. The main difference between them is that the goal of the </em>rest<em> operator is to put the rest of some provided values into an array when the </em>spread<em> operator expands iterables into individual elements.</em></blockquote><p>4. See if the verified property was cloned:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/191e4a82cf0a03a97de7e15c9d61365d/href">https://medium.com/media/191e4a82cf0a03a97de7e15c9d61365d/href</a></iframe><p>The admin object obviously has its verified property set to true because it uses the user as its prototype. But, as you can see, none of the clones has the verified property. This is because both the <em>…spread </em>operator and <em>Object.assign </em>ignore the prototype when cloning.</p><p>The prototypes of these objects:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/151bf3fda4a7554d70f83d4a63b9d69c/href">https://medium.com/media/151bf3fda4a7554d70f83d4a63b9d69c/href</a></iframe><p>To clone an object, including its prototype:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe5ad20e0434fb2737503cde23e1af68/href">https://medium.com/media/fe5ad20e0434fb2737503cde23e1af68/href</a></iframe><p>Note: <em>__proto__</em> is only a mandatory feature in web browsers, not in JS engines in general.</p><h3>TOP-1. <em>String</em> function &amp; the <em>instanceof</em> operator. <em>8%</em> of correct answers.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/370f865ed227bec399fde0b611790723/href">https://medium.com/media/370f865ed227bec399fde0b611790723/href</a></iframe><p><a href="https://t.me/intspirit/333">Try yourself</a></p><p>Absolute leader! The most difficult task out of more than a hundred specially selected non-trivial tasks. Only 2 correct answers — one of which was given by the channel admin hehe :)</p><p>What was so difficult?</p><p>If you look at the statistics of answers, you can see that the opinions of the respondents were divided approximately equally between the two wrong answers. At the time of publication of this article — 38% of developers decided that both expressions would return true and 35% of developers thought that only the second statement was true. The second half was closer.</p><p>It can be assumed that those who answered that the expression <br><em>‘Hello’ instanceof String</em> is false, while <em>String(‘Hello’) instanceof String</em> is true, knew that the instanceof operator only works with objects and does not work with primitives, but got confused with what the <em>String</em> function returns.</p><p>In fact, both expressions are false. Because:</p><ol><li>The <em>instanceof</em> operator only works on <em>objects</em>.</li><li>String literal <em>‘Hello’</em> is <em>primitive</em>.</li><li><em>String</em> calls in a non-constructor context (called without using the <em>new</em> keyword) returns a <em>primitive</em> string.</li></ol><h3>In conclusion.</h3><p>It seems that no matter how much you study JavaScript, you still learn something new. As always, we want to encourage you to keep learning the language you write every day and <strong>let’s make IT better</strong>!</p><blockquote><em>Subscribe to the</em> <a href="https://t.me/intspirit">telegram-channel</a><em> to become the “know-it-all” person in the office.</em></blockquote><blockquote><em>Follow us on </em><a href="https://intspirit.medium.com/">Medium</a><em> to not miss new articles.</em></blockquote><blockquote><em>Follow us on </em><a href="https://www.linkedin.com/company/intspirit">LinkedIn</a><em> for other cool projects we do.</em></blockquote><p>Share in the comments how many of these five quizzes did you solve correctly? Did knowledge or intuition help you?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4804c7c54eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an API using Serverless framework]]></title>
            <link>https://awstip.com/building-an-api-using-serverless-framework-cbc1e8912806?source=rss-5e5426eda6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbc1e8912806</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <dc:creator><![CDATA[Intspirit Ltd]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 09:56:25 GMT</pubDate>
            <atom:updated>2022-09-02T17:27:02.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Serverless framework logo." src="https://cdn-images-1.medium.com/max/1024/0*CSpROige5oBrUr7Z" /><figcaption><a href="https://www.serverless.com/">serverless framework</a></figcaption></figure><p>In this article we will go over the Serverless basics, its architecture and highlight the aspects of how to build a Serverless API in the AWS for your application. Also will bring the light to the situations when it’s worth doing to go on with <a href="https://www.serverless.com/">Serverless framework</a>.</p><p>If the first thoughts you have after seeing the words “s<em>erverless</em>” and “<em>lambda</em>” are a “<em>stolen server</em>” and “<em>wavelength</em>” correspondingly, then this article is for you!</p><h3>What is Serverless?</h3><p><em>Serverless</em> is a way to build and run applications &amp; services without having to manage servers. Serverless applications still run on servers, but all server management like maintaining, provisioning, and scaling is done by a cloud provider (e.g. AWS, Google Cloud Platform etc). Not that hard right?</p><p>Going next through the basics, there are two types of Serverless applications:</p><ul><li>First type deals with backend functionality as a whole — BaaS (backend-as-a-service). General idea: backend is provided and you only have to write and maintain the frontend;</li><li>Second one addresses microservices in applications only, responding to the events that occur — FaaS (function-as-a-service).Concept is simple: execute your code without thinking about servers and pay only for the compute time consumed.</li></ul><p>Further we’re going to build an API (we’d be focusing on the BaaS type of application in the article) based on serverless framework and using AWS services.</p><p>So okay, it’s time to see the picture in general, so schematically such an application will look like this:</p><figure><img alt="Serverless high-level architecture." src="https://cdn-images-1.medium.com/max/1024/0*dEEOk1l3Eg1OqI68" /><figcaption>Figure 1. Serverless high-level architecture</figcaption></figure><p>Let’s take a closer look at each component:</p><ol><li><a href="https://aws.amazon.com/api-gateway/">AWS API GATEWAY</a> is an AWS service for building APIs. Any request sent here triggers a lambda (in fact, it can be anything from AWS Kinesis to even a regular EC2, that’s a topic for another article) that’s tied to a specific endpoint. Amazon API Gateway allows you to create REST, HTTP, and WebSocket APIs at any scale.</li><li><a href="https://aws.amazon.com/lambda/">AWS Lambda</a> is a service that lets you run your code without managing servers. Lambda performs all of the administration of the compute resources, capacity provisioning and automatic scaling. AWS Lambdas will act as controllers for our API.</li><li>Everything else — handlers, services, guards — is our logic built according to a pattern we choose. This logic will be n̶e̶a̶t̶l̶y̶ ̶s̶t̶r̶u̶c̶t̶u̶r̶e̶d̶ minced together and put into Lambda handlers.</li><li>DB — our database. <a href="https://www.serverless.com/">AWS Documentation</a> advises us to use <a href="https://aws.amazon.com/dynamodb/">DynamoDB</a> (AWS noSQL is not advised here). But in reality, we can use any DB we are familiar with, such as RDS or DocumentDB (translation for the uninitiated — PostgreSQL or MongoDB).</li><li><a href="https://aws.amazon.com/cloudformation/">AWS CloudFormation</a> is a service that gives developers and businesses an easy way to create a collection of related AWS and third-party resources, and provision and manage them in an orderly and predictable fashion.</li></ol><p>Together, all AWS Serverless services (API Gateway, Lambda and etc.) are referred to as the <em>AWS Serverless Stack</em>. When these technologies first appeared, working with them was extremely inconvenient due to the complexity of describing CloudFormation for both API Gateway and Lambda. This issue was later resolved with the Serverless Framework.</p><blockquote>Serverless Framework is an open source devOps framework for configuring API Gateway and Lambda.</blockquote><p>Later in the article we will see how simple it is to work with.</p><h3>Why use Serverless?</h3><p>Despite a number of difficulties and limitations that a Serverless application developer will have to face (more on that below, hehe!), the Serverless infrastructure also has a number of undeniable <strong>advantages</strong>:</p><p><strong>1. Simple deployment.</strong></p><p>The life of a DevOps engineer becomes easier and more enjoyable when deploying Serverless apps rather than when setting up and configuring an application in <a href="https://aws.amazon.com/ec2">Amazon ЕС2</a>. All you need is:</p><ul><li>Credentials for an AWS account with the necessary access.</li><li>And… that’s it — <a href="https://aws.amazon.com/cloudformation/">CloudFormation</a> deployment will be launched with one command.</li></ul><p>Some services (example — <a href="https://aws.amazon.com/sqs/">SQS</a> — message queues for microservices, distributed systems, and Serverless applications) cannot be created by the Serverless framework. They will have to be added manually through AWS UI, and then credentials of these freshly created services will have to be manually added into the Serverless config.</p><p><strong>2. Out of the box scalability.</strong></p><p>A simple example: when the horizontal load on your application increases, instead of moving to a more powerful server you need… nothing. Well, you could play with your lambdas’ concurrencies, but that’s not always necessary. <em>(Concurrency is the number of requests that your function is serving at any given time. When your function is invoked, Lambda allocates an instance of it to process the event. When the function code finishes running, it can handle another request. See </em><a href="https://docs.aws.amazon.com/lambda/latest/operatorguide/scaling-concurrency.html"><em>this</em></a><em> to know more)</em>. At the moment of peak load, the number of simultaneously running lambdas grows up to 10,000 and none of them are binded to the computing power of your EC2 VMs.</p><p><strong>3. Easy interaction between your services and AWS services.</strong></p><ul><li>Most of the work, if not all of it, has already been done for you. There are 40+ Lambda templates for the most common use cases (e.g. microservice-http-endpoint, dynamodb-process-stream, sns-message, sqs-poller,cloudwatch-alarm-to-slack-python, s3-get-object, etc.)</li><li>AWS documentation… it’s really good!</li><li>Ease of interaction. Again, in most cases, you will not have to get inside the AWS UI to redo service settings. Serverless app can do it out of the box (with very rare exceptions).</li></ul><p><strong>4. Cost.</strong></p><p>You only pay for the time that Lambdas work. No requests means no work time for lambdas, which means no payments have to be made.</p><p>And now f̶i̶n̶a̶l̶l̶y̶,̶ ̶t̶h̶e̶ ̶d̶e̶s̶e̶r̶t̶!̶ the <strong>disadvantages</strong> of course:</p><p><strong>1. Cost.</strong></p><p>What do you mean? Wasn’t this an advantage?</p><p>There are about 2600000 seconds in a month. If your EC2 has been working hard all this time, you will still pay a fixed amount ($44 and up). But if your AWS API GATEWAY was constantly bombarded by thousands upon thousands of requests, and lambdas were constantly being invoked, this will cost a pretty penny. You will pay both for the number of requests and for “megabytes per time” <em>(The cost of lambda work is calculated by how much RAM was used and for how long)</em>.</p><p>Let’s count together. Here is a CloudWatch log for an invoked lambda (real project, which resolves the relationship between three third-party services):</p><figure><img alt="CloudWatch log of invoked lambda function." src="https://cdn-images-1.medium.com/max/1024/0*AweIp97ljQ8iYrVk" /><figcaption>Figure 2. CloudWatch log of invoked lambda function</figcaption></figure><p>The cost of this particular call (outside the free-tier) is about $0.0000085. But what if it was invoked a million times? (~$8.5) And if you have 10 such lambdas?(~$85) Or 100? (~$850)</p><p><strong>2. Debugging.</strong></p><p>Even if you have a well thought out system of logs and they do not spaghetti into <a href="https://aws.amazon.com/cloudwatch/">CloudWatch</a> (which they tend to do unless properly configured: each lambda invocation creates a new Lambda version and randomly pours logs into CloudWatch), debugging remains a non-trivial task.</p><p><strong>3. Relocating your application.</strong></p><p>You are tied to AWS. Once and for all. Take it as a given. Moving to, let’s say, Google Cloud Platform will, of course, be cheaper than writing your application from scratch, but not exponentially.</p><p><strong>4. Security.</strong></p><p>A server that runs Serverless functions runs them for myriad customers, which opens up a lot of security concerns. TechRepublic sister site <a href="https://www.zdnet.com/">ZDNet</a> lists <a href="https://www.zdnet.com/article/the-top-10-risks-for-apps-on-serverless-architectures/">10 potential security risks associated with Serverless computing</a>, which include:</p><ul><li><strong>Function event data injection</strong>, which is an SQL injection-style attack on a server running Serverless functions;</li><li><strong>Insecure Serverless deployment configuration</strong>, which accounts for any number of mistakes on the administrative end that leave Serverless computing servers open to man-in-the-middle attacks;</li><li><strong>Inadequate monitoring and logging of functions</strong>, which can tip administrators off to attackers performing reconnaissance to test the potential for attack;</li><li><strong>Insecure third-party dependencies </strong>— Serverless functions that call on third-party dependencies can put data at risk if those dependencies contain malicious code;</li><li><strong>DDoS attacks</strong> on Serverless platforms can overload them and take down functionality for multiple customers at the same time.</li></ul><p><strong>5. Limitations of Serverless API.</strong></p><ul><li>AWS API GATEWAY PAYLOAD LIMIT — 10 MB (<a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html">link</a>) — what size of incoming request’s body can AWS API Gateway “digest”</li><li>AWS Lambda Payload Limit — 6 MB (<a href="https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html">link</a>) — what size of incoming event’s body can AWS Lambda “digest”.</li></ul><p>What does this mean? This means that unless we d̶a̶n̶c̶e̶ ̶w̶i̶t̶h̶ ̶a̶ ̶t̶a̶m̶b̶o̶u̶r̶i̶n̶e̶ put our head down and work around it, we cannot put a body over 6 MB into a single POST request to our lambda. Sad but true story, we faced towards both limitations in a real project.</p><h3>How to use Serverless?</h3><p>We have covered the structure of Serverless applications, but have not even come close to the most important thing — how does the Serverless framework actually work?</p><p>So, once the logic of our application is ready, and once we’ve created thousands of lines of code, serverless finally comes into play. We just give a command to deploy (with the <em>serverless deploy</em> command)… and nothing. First, we must put together a serverless configuration file, in which we explain to the framework what comes from where, what connects with what, and which rights to give stuff.</p><p>AWS API Gateway acts as our endpoints, and AWS Lambda acts as the controller. The Serverless framework itself can, of course, create boilerplates. But we will do it another way. We will do everything manually. A textbook <em>helloworld</em> will look like this, done step by step:</p><ol><li>Install Serverless globally: <em>`npm install -g serverless`</em></li><li>Create a folder for our project with any name.</li><li>Create a <em>lambdas</em> folder inside the project folder.</li><li>Inside the <em>lambdas</em> folder, create a <em>helloworld.js</em> file with the following content:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a73d3bec615d6aa24b047e8341332e0/href">https://medium.com/media/2a73d3bec615d6aa24b047e8341332e0/href</a></iframe><p>This handler is our lambda that will be called when accessing a specific url, which we will set in the config. This, basically, is just a basic function which accepts up to 3 arguments:</p><blockquote>function(event, context, callback) {}</blockquote><p>One of them is not even necessary for our helloworld, but still:</p><ul><li><em>event</em> — a basic request with URL, METHOD, HEADERS, BODY, etc.</li><li><em>context</em> — contains information about the invocation, function, and execution environment</li><li><em>callback</em> — essentially a basic callback used for synchronous code. This callback will be executed when all other code has been executed. Roughly speaking, this is <em>return</em> (and in the lambda, return is an analogue of the <em>send </em>method in an Express server), but synchronous.</li></ul><p>In our case, the lambda function simply always sends a standard response — status 200, body { message: ‘Hello world’ }.</p><p>5. Also inside the project folder, let’s create a <em>serverless.yml</em> and fill it like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b70b9380bf0d2cfc087a6ed6537dc1a2/href">https://medium.com/media/b70b9380bf0d2cfc087a6ed6537dc1a2/href</a></iframe><p><em>Note: serverless.yml created according to the Dockerfile principles, hence the Python-style whitespaces </em>^^</p><p>6. We are almost ready for the deployment, but… we still need AWS account credentials. Set them up from any terminal (Example for MacOS &amp; Ubuntu):</p><ul><li>export AWS_ACCESS_KEY_ID=&lt;<em>your-key-here</em>&gt;</li><li>export AWS_SECRET_ACCESS_KEY=&lt;<em>your-secret-key-here</em>&gt;</li></ul><p>7. Now, boldly execute using the “<em>sls deploy</em>” command</p><p>8. Once deploy has finished, we will see something like this:</p><figure><img alt="The console says the service is deployed to stask." src="https://cdn-images-1.medium.com/max/648/0*tX4A6TCg5d4ahW5M" /></figure><p>Our first endpoint is ready! Now sending a GET request to <a href="https://asudrow3hk.execute-api.eu-west-1.amazonaws.com/hello">https://asudrow3hk.execute-api.eu-west-1.amazonaws.com/hello</a> will return us a response of {“message”:”Hello world”}.</p><figure><img alt="A screenshot of Stacks in the AWS CloudFormation." src="https://cdn-images-1.medium.com/max/274/0*qJ12ZXEE9Je4haZb" /><figcaption>Figure 3. AWS CloudFormation-&gt;Stacks</figcaption></figure><figure><img alt="A screenshot of AWS Buckets." src="https://cdn-images-1.medium.com/max/553/0*J9x4xvLLvzpLXo8T" /><figcaption>Figure 4. AWS Buckets</figcaption></figure><figure><img alt="A screenshot of AWS Lambdas." src="https://cdn-images-1.medium.com/max/307/0*-ju7nE-3LMIf1o7F" /><figcaption>Figure 5. AWS Lambdas</figcaption></figure><h3>Advanced serverless.yml configuration.</h3><p>There are many addons &amp; plugins for the Serverless framework, whether official or not so much. Here are some of the real must-have ones:</p><p>1. <a href="https://www.npmjs.com/package/serverless-dotenv-plugin">serverless-dotenv-plugin </a>— allows getting variables from <em>.env</em> instead of hardcoding them inside <em>serverless.yml</em>.</p><p>It would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83f8202614fc254fba22560a75365515/href">https://medium.com/media/83f8202614fc254fba22560a75365515/href</a></iframe><p><em>Note: If we want to make more than one stage/env, we need to perform the following (in the simplest way):</em></p><ul><li><em>Create a desired number of serverless.yml files and accordingly name them </em><strong><em>serverless.stageName.yml</em></strong></li><li><em>For each of them, inside the </em><strong><em>provider</em></strong><em> section in the </em><strong><em>stage</em></strong><em> property put a corresponding stageName</em></li><li><em>Create the same amount of </em><strong><em>.env.stageName</em></strong><em> files</em></li><li><em>Deploy using the following command: “export NODE_ENV=stageName &amp;&amp; sls deploy -c ./serverless.stageName.yml”</em></li></ul><p>Also keep in mind that lambda names for different environments should be different.</p><p>2. <a href="https://www.npmjs.com/package/serverless-ignore">serverless-ignore</a> — basically <em>.gitignore</em>. Even the syntax is the same. Used to create an <em>.slsignore </em>file in the root folder of the project. All the source files that you specify in this file will not be included in the deployment. Be sure to include your .env.*</p><p><em>Note: If AWS packages appear in your lambdas (let’s say for working with a S3 bucket, etc.), you can add the line node_modules/aws-sdk/*. AWS already has it, and you will save on the deployment size).</em></p><p>In order to connect plugins, it is not enough to simply install them (these are ordinary npm packages and they are installed accordingly). You also need to add the <em>plugins</em> section to <em>serverless.yml</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50c7704a274f99405996a89390febd3e/href">https://medium.com/media/50c7704a274f99405996a89390febd3e/href</a></iframe><h3>Access issues. AWS IAM policies.</h3><p>If your lambdas work with AWS services, you need to clearly define roles &amp; policies. Example for reading and deleting from a bucket:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/908422c76cb10de83ce48bc27eeb8e19/href">https://medium.com/media/908422c76cb10de83ce48bc27eeb8e19/href</a></iframe><p>You can add an ‘iam’ section to:</p><ul><li>“provider” section — in this case all listed policies will be given to ALL lambdas within your Serverless app</li><li>any individual lambda section. In this case, all listed policies will be given only to this particular lambda</li></ul><p>The easiest <em>resource</em> to use is <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a>. In case of a bucket, you can add path to the ARN link to specify where exactly in the bucket your lambda can roam, or simply add `/*`, which means access to the entire bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PRQv5G_TnS3gKYoH" /><figcaption>Figure 6. An example of where to get ARN</figcaption></figure><h3>“timeout” property.</h3><p>Another important lambda property is the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html">timeout</a>. It’s not what you think. AWS API Gateway has a default timeout limit of 15 seconds. But lambda’s timeout is its lifetime, which can be set to up to 900 seconds.</p><p>A real situation: the lambda is overloaded with logic or a lot of sequential requests to third-party-services, and takes longer than 15 seconds to finish executing. It might finish the task, if within the maximum timeout of 900, but you will not get an answer.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a7410c95ab6d989fdb14cce01728cce/href">https://medium.com/media/8a7410c95ab6d989fdb14cce01728cce/href</a></iframe><h3>Lambda structure.</h3><p>Of course in our helloworld example, everything is plain and simple. Once you start working on more complex stuff, you should structure your code according to whichever pattern you prefer.</p><p>It is also recommended to move from JS to TS. This will allow you to avoid a lot of pitfalls while writing a code. In our <em>helloworld</em> case, the tsc command (or any other transpiler) would simply be added to the deployment launch script, and the path to the lambda handlers in <em>serverless.yml</em> would be taken directly from build/.</p><h3>Lambda triggers.</h3><p>Although the article is called “building an API using Serverless”, keep in mind that a request from the AWS API Gateway is far from the only lambda trigger out there. Events of many AWS services can act as a lambda trigger. Some examples include upload to AWS S3, message in SQS, or even another lambda (usually via <a href="https://aws.amazon.com/step-functions/?step-functions.sort-by=item.additionalFields.postDateTime&amp;step-functions.sort-order=desc">AWS Step Functions</a>). It’s even possible to turn on a schedule for lambda execution.</p><h3>In conclusion.</h3><p>As a parting word, we will say: you must be 101% sure that you need a Serverless application. You shouldn’t go the Serverless way just because you’ve been told that “it’s what the cool kids do nowadays”. Weigh all the pros and cons and decide for yourself.</p><p>Article written by an engineer from <a href="https://intspirit.com/">Intspirit</a>.</p><blockquote>Follow us on <a href="https://intspirit.medium.com/">Medium</a> to not miss new articles.<br>Follow us on <a href="https://www.linkedin.com/company/intspirit/">LinkedIn</a> and <a href="https://www.facebook.com/Intspirit/">Facebook</a> to be aware of other awesome projects we do.<br>Try yourself in our <a href="https://t.me/intspirit">telegram-channel</a> with JS quizzes frequently asked in job interviews.</blockquote><p>Thank you for reading,<br>and let’s make IT better!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbc1e8912806" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/building-an-api-using-serverless-framework-cbc1e8912806">Building an API using Serverless framework</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top of JS Topics mostly failed by developers]]></title>
            <link>https://intspirit.medium.com/top-of-js-topics-mostly-failed-by-developers-53397f13eb78?source=rss-5e5426eda6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/53397f13eb78</guid>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[hoisting]]></category>
            <category><![CDATA[this]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Intspirit Ltd]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 13:06:56 GMT</pubDate>
            <atom:updated>2023-01-24T16:13:27.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Top-5 most failed JS topics based on quizzes statistics." src="https://cdn-images-1.medium.com/max/1024/1*CQUz0ywpQoLa9A3ziR9J5w.png" /><figcaption>Top-5 most failed JS topics</figcaption></figure><p>How often do you ask yourself while coding: «What kind of magic is going on here?»</p><p>No magic, it’s just a JavaScript we don’t know.</p><p><strong>Intro</strong></p><p>Some time ago we created a <a href="https://t.me/intspirit">telegram channel</a> with JS quizzes. Today we’d like to share statistics on what JS aspects are the most hardest for developers based on the failed answers percents.</p><p><strong>About quizzes</strong></p><p>First of all, we have to say what those quizzes are.</p><p>The quizzes we post cover the JS basics but not in a simple way. To answer correctly a respondent has to have a deep JS knowledge and understand how an engine interprets the instructions.</p><p>For example, every developer knows how to declare a variable in JS. One of the special words has to be used: <em>var</em>, <em>let</em> or <em>const</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afa05a7fc1d1abc9c8dc163a5795402c/href">https://medium.com/media/afa05a7fc1d1abc9c8dc163a5795402c/href</a></iframe><p>Many developers know how this instruction will be handled by the engine. It divides this instruction into two ones:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab477cbd1de882643980bf8c44516e5a/href">https://medium.com/media/ab477cbd1de882643980bf8c44516e5a/href</a></iframe><p><em>Variable declaration</em> (the first line) is moved by the engine on the top of their scope before script running. And <em>variable initialisation</em> (the second line) is handled just in time the engine is on that line of the code.</p><p>But how many developers know how the engine interprets the following piece of code?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca413c2d05e03e526406839abd072de6/href">https://medium.com/media/ca413c2d05e03e526406839abd072de6/href</a></iframe><p>To answer correctly a developer has to know how the engine handles the multi declarations of the same variable name and which has more priority: variable declaration or function declaration?</p><p>This question is also about variable declaration, but does not look so easy.</p><p>Do you know the result? <a href="https://t.me/intspirit/161">Try yourself.</a> (Please don’t be embarrassed by the Russian language in the question — all you need is to choose the correct answer)</p><p>When we explain how exactly that piece of code is processed, 94% of respondents admitted that they didn’t know it works that way (ah, numbers are a stubborn thing!)</p><figure><img alt="Statisctics vs Machine Learning &amp; AI &amp; Deep learning." src="https://cdn-images-1.medium.com/max/496/1*iKCeE1o_qQvm46931LJNag.png" /><figcaption><a href="https://me.me/i/statistics-meme-36faf34b591d49f09bc15b57f436f32a">Statistics never lie</a></figcaption></figure><p><strong>About calculations</strong></p><p>The calculation principle is simple — we divided all quizzes by topic (15 topics in total) and calculated the average percentage in each topic.</p><p>There is one inaccuracy in our approach, which is unlikely to have a significant impact on the result. To solve some of the quizzes, the developer must understand several topics, and in case of an incorrect answer, it is not known which one of them led to it. Such quizzes are placed in several categories at once.</p><p>Don’t think about the numbers below as constants. Everyday new developers are solving our quizzes and values are changing. However, our observations showed that regardless of the number of answers, the rating does not change much and the overall picture remains the same.</p><p>Now, when you know what kind of quizzes our statistics is based on and how we calculate it, let’s see <strong>the TOP 5 of most failed JavaScript topics.</strong></p><p><strong>TOP-5: Variable Scope. 46% of correct answers.</strong></p><p>For us this was the most fruitful topic, on which we easily came up with various challenges. To be honest, we didn’t expect the scope to take only the fifth place, as it seems more difficult to us. But the statistics know better.</p><p>An example of scope quiz:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cd2faebe798e6ddd027dc5d5a9b6fc2/href">https://medium.com/media/6cd2faebe798e6ddd027dc5d5a9b6fc2/href</a></iframe><p><a href="https://t.me/intspirit/202">Try yourself</a>.</p><p><strong>TOP-4: Promises. 43% of correct answers.</strong></p><p>Promises are a pretty straightforward tool to use. However, when a programmer needs to know how they work “from the inside” in order to answer a quiz, not many of them know the answer.</p><p>For example to answer the following quiz you need to know the algorithm of Promise’s state changing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90558f7e0475a8ab21f321626b36b7fc/href">https://medium.com/media/90558f7e0475a8ab21f321626b36b7fc/href</a></iframe><p><a href="https://t.me/intspirit/194">Try yourself</a>.</p><p>If you want to dive deeper in how Promises work under the hood, read this article:</p><p><a href="https://intspirit.medium.com/deep-deep-deep-into-promises-8dc72e86487a">Deep deep deep into Promises</a></p><p><strong>TOP-3: Hoisting. 34% of correct answers.</strong></p><p>We believe that hoisting is one of the most interesting topics in JavaScript because it makes you think about how JavaScript works. It makes you know that the engine processes a JS program in two stages. Which in turn can lead you to wonder if it’s an interpreted language or not.</p><p>So ,with a deep understanding of hosting, you can get very close to the language you’re actually working with.</p><p>One of many examples of hoisting:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cd2c5b356de16751ba01cf6fb6f4a31/href">https://medium.com/media/3cd2c5b356de16751ba01cf6fb6f4a31/href</a></iframe><p><a href="https://t.me/intspirit/279">Try yourself.</a></p><p><strong>TOP-2: ES6 modules. 32% of correct answers.</strong></p><p>Can we change an imported variable so that the change is applied in the source module? Will an imported variable change if it is changed asynchronously after being exported? Our statistics show that only 32% of developers in avarage know the answers to these and other questions about modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a188b42b699c960dca13490418e1e985/href">https://medium.com/media/a188b42b699c960dca13490418e1e985/href</a></iframe><p><a href="https://t.me/intspirit/106">Try yourself.</a></p><p>This article will help you understand all the nuances of ES6 modules (you have no idea how many of them) and become a pro in this complex topic:</p><p><a href="https://javascript.plainenglish.io/50-shades-of-es6-modules-95cd0b016156">50 shades of ES6 modules</a></p><p><strong>TOP-1: “this” variable. An execution context. 30% of correct answers.</strong></p><figure><img alt="Meme: Oh my God I’m the winner." src="https://cdn-images-1.medium.com/max/600/0*T5fGQg2P3ESpgqPe" /><figcaption><a href="https://sayingimages.com/winner-meme/">this</a></figcaption></figure><p>We have a winner! Are you surprised? We are not! Our 12 years of experience of interviewing the JS engineers tell us the same. Understanding of “this” has always been the most difficult challenge for developers. And this is one of the reasons why React.js migrated from OOP to functional programming.</p><p>If you are one of the developers feeling confused about an execution context, do not give up, you just need a little more practice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f581810edece49013220c6c884999bfa/href">https://medium.com/media/f581810edece49013220c6c884999bfa/href</a></iframe><p><a href="https://t.me/intspirit/168">Try yourself.</a></p><p><strong>In conclusion</strong></p><p>It is unfortunate to hear that many developers do not consider it necessary to learn JavaScript in its entirety with all its features and corner cases. Why know what the code will output if you can run and check. Unfortunately, most developers think so. Beginners in general often spend almost no time on JS itself and immediately move on to learning frameworks. At Intspirit, we believe that there is nothing in the language that is not important and not worthy of study. Javascript is a complex language with many pitfalls and learning it from start to finish is very difficult, if not impossible. But that doesn’t mean we shouldn’t try.</p><figure><img alt="Patric tries to understand JS." src="https://cdn-images-1.medium.com/max/500/0*iWdVMf882UZ-H5hO" /><figcaption><a href="https://www.freecodecamp.org/news/explaining-the-best-javascript-meme-i-have-ever-seen/">Ladies and gentlemen, meet JavaScript</a></figcaption></figure><p>This TOP of “failures” only includes topics that can be classified. Besides them we post quizzes covering more specific JS features. Next time we’ll share TOP most failed quizzes among all topics, <a href="https://medium.com/@intspirit">subscribe</a> to not miss.</p><p>Subscribe to the <a href="https://t.me/intspirit">telegram-channel</a> to become the “know-it-all” person in the office. Follow us on <a href="https://www.linkedin.com/company/intspirit">LinkedIn</a> for other cool projects we do.</p><p>What is the most difficult thing about JS for you? Share in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53397f13eb78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to drag anything and drop anywhere?]]></title>
            <link>https://intspirit.medium.com/hello-dnd-a4a6ce4b850e?source=rss-5e5426eda6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4a6ce4b850e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[drag-and-drop]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[dnd]]></category>
            <dc:creator><![CDATA[Intspirit Ltd]]></dc:creator>
            <pubDate>Thu, 16 Jun 2022 13:29:50 GMT</pubDate>
            <atom:updated>2022-11-27T15:02:01.991Z</atom:updated>
            <content:encoded><![CDATA[<h4>A bit of handmade magic <em>(it won’t work without magic, proved!)</em></h4><figure><img alt="Drag &amp; drop — do it yourself or use ready-made" src="https://cdn-images-1.medium.com/max/484/1*KoZSsDT8l3ECRB3GbEwRTA.png" /></figure><p><strong>First word</strong></p><p>Drag &amp; drop functionality allows to easily drag interface elements from one place to another. Due to its simplicity and ease of use, drag &amp; drop can be found in many graphical interfaces. And, of course, there already are tons of ready-made solutions that make implementing such functionality a piece of cake.</p><p>However, drag &amp; drop libraries are not always flexible enough to meet all the business requirements. When the requirements are different from the standard implementation, it is often faster to write your own drag &amp; drop functionality rather than to add crutches for an existing codebase. Not to mention, your own implementation is easier to maintain in the face of frequently changing requirements (clients, clients and again clients hehe!).</p><p>It was also the case for us in one of our projects. <em>React-beautiful-dnd</em> is really <em>beautiful</em>, but in an attempt to customize it to fit our needs, it has acquired a lot of hacks: some advised by its authors, some being our original solutions. In the end, we decided to develop a completely custom solution from the ground up and kick the <em>beautiful </em>off.</p><figure><img alt="A man with a gun." src="https://cdn-images-1.medium.com/max/300/1*LQBkzPHmUs7ONsxn2vDd-A.png" /><figcaption><a href="https://i.kym-cdn.com/photos/images/original/001/578/173/f57.jpg">bang bang</a></figcaption></figure><p>In this article we’ll discuss the intricacies of implementing drag &amp; drop into your own project. Gonna use React as the environment for the examples.</p><p><strong>Introduction</strong></p><p>When dragging &amp; dropping elements in a list, we need to (ugh, every time!) remember the positions of the elements.</p><p>Most of the time, you already have an initial list that needs to be displayed in a specific order. At this stage, we need to initialize the elements of the list with the values of the initial positions. Usually a certain constant is chosen as a step. The first element in the list receives the value of this step, the positions of the following elements are calculated by adding the step to the previous element.</p><p>The new position of a <em>draggable</em> element is calculated by taking the average between adjacent elements. For example, to move an element in a vertical list, the formula would look like this:</p><blockquote>newPosition = (topItem.position + dowItem.position) / 2</blockquote><p>For easier division, it is recommended to use float numbers for the positions of the draggable elements.</p><p>We will make a simplified example — without Redux and backend, but will assume 2 things — that at a later stage the positions of the elements will have to be stored somewhere, and that HTML elements have some level of complexity (nesting).</p><p><strong>HTML Drag &amp; Drop</strong></p><p>Let’s take a look at the ̶b̶o̶r̶i̶n̶g̶ ̶s̶t̶u̶f̶f̶ <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API">documentation</a>.</p><blockquote>draggable<em> — </em>an attribute that indicates that the element can be dragged.</blockquote><p>Methods of a <em>draggable</em> element:</p><blockquote>onDragStart<em> </em>— event handler for starting to drag an element.</blockquote><blockquote>onDrag<em> — </em>event handler for dragging an element.</blockquote><blockquote>onDragEnd<em> — </em>event handler for the end of dragging an element.</blockquote><p>Methods for the area we’re dragging the elements into:</p><blockquote>onDragEnter<em> — </em>event handler for entering the area of the element which we’re dragging to.</blockquote><blockquote>onDragLeave<em> — </em>event handler for exiting the element area.</blockquote><blockquote>onDragOver — event handler for dragging above the current element.</blockquote><blockquote>onDrop — event handler for the drop (the same as end of dragging).</blockquote><p><strong>Let’s start! onDragStart!</strong></p><p>Let’s create a list of <em>draggable </em>elements:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39589d42c363936d9de19fb0dbadba36/href">https://medium.com/media/39589d42c363936d9de19fb0dbadba36/href</a></iframe><p>See, it doesn’t look too bad already, right?!</p><figure><img alt="A list with draggable elements." src="https://cdn-images-1.medium.com/max/512/1*x1vEgQ9qICh--WJwbYsd3g.gif" /><figcaption>That’s how draggable elements look like</figcaption></figure><p>But so far this is only visuals. We will have to write the entire logic of the drag and drop ourselves.</p><p>First I would like to add styles to the list. Let’s make a draggable element disappear from the list and remain stuck to the mouse cursor.</p><p>To do this, let’s add a listener to the <em>onDragStart</em> event:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6f350528ade5948c8194c8530ef9bba/href">https://medium.com/media/c6f350528ade5948c8194c8530ef9bba/href</a></iframe><p>And let’s also implement the <em>onDragStartHandler</em> handler, which will remember the index of the <em>draggable</em> element in order to add styles to it later:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/015cff762968dca7ba1cee356c2a3089/href">https://medium.com/media/015cff762968dca7ba1cee356c2a3089/href</a></iframe><p>This is where the magic begins. Caution — not a long read!</p><p>Drag &amp; drop’s default behavior is to take a screenshot of the <em>draggable</em> element at the time of the drag and display it near the mouse cursor. If in the <em>onDragStart</em> event handler we save the draggable element’s index synchronously and use it to set styles for the element, then new styles can appear on both — the element in the list and the screenshot on the mouse, as well as only on the dragged element. This depends on whether the engine creates a screenshot before applying new styles on the element or after. To make sure that the screenshot remains unchanged and styles are applied only to the element, we wrap the <em>setDraggableIndex</em> function call into a <em>setTimeout </em>function. This way, we take the operation of saving the index out of the stream, so that the engine takes a screenshot of the element with the old styles — before the new styles are applied to the element.</p><p>We should also mention the <em>opacity</em> property. As you can see in the animation above — the screenshot of the element hanging by the mouse cursor has <em>opacity</em>. The element receives this property from the internal processing of the event, and there don’t seem to be any standard way to influence it — delete or change it.</p><p>And, of course, the index must be reset at the end of the drag:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51d162947165100d6e9523bf5d3f1f10/href">https://medium.com/media/51d162947165100d6e9523bf5d3f1f10/href</a></iframe><figure><img alt="An element is removed from the list when dragged." src="https://cdn-images-1.medium.com/max/512/1*gtEJKgM9JBGFY8N3uIT9JA.gif" /><figcaption>Hid a draggable element from the list.</figcaption></figure><p>See? Much better.</p><p>But all we did was just adding some styles:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6890ee731d2773b02bdc8d5997ab9c5/href">https://medium.com/media/e6890ee731d2773b02bdc8d5997ab9c5/href</a></iframe><figure><img alt="Hagrid says to Harry that he is a developer." src="https://cdn-images-1.medium.com/max/500/1*uuoG1OK_h_2FpL16Ha3NPQ.jpeg" /><figcaption>hehe</figcaption></figure><p><strong>Hover? No. onDragEnter.</strong></p><p>At the moment of dragging, it is often necessary to highlight the area where the element is currently located, so that the user can see where it will go once the mouse button is released.</p><p>Sadly, CSS doesn’t have something like <em>hover</em> for DnD. But we will write our own, it will be even better. Trust me, I’m an engineer!</p><p>To do this, we will use the <em>onDragEnter</em> and <em>onDragLeave</em> events to save the index of the element we are currently above, as well as a <em>&lt;Separator /&gt;</em> component that will clearly show the user where the element will go in the list if the mouse button is released.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a223e41d2a242010fb3596ce9d33f7ea/href">https://medium.com/media/a223e41d2a242010fb3596ce9d33f7ea/href</a></iframe><p>In our case, the <em>&lt;Separator /&gt;</em> component will look like a simple line:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8dc6db3a993c8615ab7286f41e33b47/href">https://medium.com/media/c8dc6db3a993c8615ab7286f41e33b47/href</a></iframe><p>But you can use any visual separator you like.</p><p>The <em>onDragEnter</em> and <em>onDragLeave</em> events have their own pitfalls. If the drag area has multiple nestings, these events may fire multiple times. This will create a discrepancy where the hover area will be considered hovered when it is not, or vice versa. For example, if we have an error in the calculations, and the depth value remains positive, then we will not be able to track when we left the tracked area:</p><figure><img alt="Incorrect highlights of drop areas when dragging." src="https://cdn-images-1.medium.com/max/512/1*Xa-vX_PnJUaHdcxI7Z62UQ.gif" /><figcaption>Incorrect processing of multiple <em>onDragEnters and onDragLeaves leads to w</em>rong highlights.</figcaption></figure><p>To fix this bug, we will use a little trick.</p><p>Let’s create a variable called <em>dropDepthRef.current</em>, in which we will store the depth counter. Each time the <em>onDragEnter</em> event fires, we will increment the counter by 1. And when the <em>onDragLeave</em> event fires, decrement the counter by 1 and reset the index only if the counter is 0, which will mean that we have left the top element:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da071b893000bd7bdaee7a40d718240b/href">https://medium.com/media/da071b893000bd7bdaee7a40d718240b/href</a></iframe><p>Note that we are using <em>useRef</em> to store the counter. There is a reason for it. If you store the variable in <em>state</em>, the component will re-render every time either one of <em>onDragEnter</em> and <em>onDragLeave</em> events fire. Firstly, we do not need to re-render the component, and secondly, this can lead to an error in the depth calculation if the new event fires at the time of the state update.</p><p>Another bug you may encounter is incorrect rendering of the <em>&lt;Separator /&gt;</em> element. In the example above, we used this common construction:</p><blockquote>{index === dragOverIndex &amp;&amp; &lt;Separator /&gt; }</blockquote><p>When using such a construct in your code, the fastest QA engineers will notice a case where, when quickly moving the cursor between elements, one of the <em>onDragLeaveHandler</em> is skipped due to component re-rendering, which leads to a depth calculation error and, as a result, the bug shown in the animation above. And it is quite difficult to escape the fastest one. Trust me.</p><p>How do we fix this? Instead of conditionally rendering the <em>&lt;Separator /&gt;</em> component, move the rendering logic inside the component:</p><blockquote>&lt;Separator active={list.length === dragOverIndex} /&gt;</blockquote><p>Now the <em>&lt;Separator /&gt; </em>looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7b7ac8283ff9d4bd714b79ef9d0a4fc/href">https://medium.com/media/e7b7ac8283ff9d4bd714b79ef9d0a4fc/href</a></iframe><p>And this is what we get:</p><figure><img alt="Highlighting a drop area with a line when draggable element is over it." src="https://cdn-images-1.medium.com/max/489/1*11vx07bP02g-4YNjzCtXSg.gif" /><figcaption>Highlighting a drop area</figcaption></figure><p>A small note — to also be able to drop to the end of the list, do not forget to add a listener there:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/604e74276d8d4ce0dd4ac78cbd5d55f8/href">https://medium.com/media/604e74276d8d4ce0dd4ac78cbd5d55f8/href</a></iframe><p>This is what the code looks like at this stage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c809b2bb3c4b9915d8e673740fa5a070/href">https://medium.com/media/c809b2bb3c4b9915d8e673740fa5a070/href</a></iframe><p><strong>Finally, not just drag! Also drop. onDrop!</strong></p><p>Let’s add an <em>onDrop</em> event handler. Now, the <em>draggable</em> element wrappers will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf4d0c26678afd4d855b5314f0998bfe/href">https://medium.com/media/bf4d0c26678afd4d855b5314f0998bfe/href</a></iframe><p>In the handler, we remove the <em>draggable</em> element from the list and insert it with a new position calculated as the arithmetic average of the positions of the top and bottom elements relative to the current <em>dropIndex</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f6642249c07bcae872709bb8847599f/href">https://medium.com/media/1f6642249c07bcae872709bb8847599f/href</a></iframe><p>It’s important to note that the calculation of the position will depend on the data structure, performance requirements and the final goals. Our goal here is to make it descriptive. And fast ;-)</p><p>Launch, check and … it does not work. Needs a little more magic!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*tX3ez_H4MeJAKqK8rn7-4Q.png" /><figcaption><a href="http://www.quickmeme.com/img/23/230e49ffd0916329b183ed306f9795b2fa0a8c6026a1a123f04d156608844741.jpg">Needs more magic</a></figcaption></figure><blockquote>const onDragOverHandler = (e) =&gt; { e.preventDefault(); };</blockquote><p>This is non-obvious particularity of <em>Drop Targets</em>. Details can be found <a href="https://developer.mozilla.org/en-US/docs/web/api/html_drag_and_drop_api/drag_operations#specifying_drop_targets">here</a>.</p><p>And…done!</p><figure><img alt="Drag and drop an element in the list." src="https://cdn-images-1.medium.com/max/489/1*zSrJ9l0neBkQqGFNN6PVXw.gif" /><figcaption>We finally can drop!</figcaption></figure><p><strong>Drag but deeper.</strong></p><p>Not enough special effects? We can change the default behavior of taking a screenshot while dragging. Using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/setDragImage"><em>setDragImage</em></a> method available on the <a href="https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer"><em>dataTransfer</em></a> event object, we can create our own screenshot using any element and any formula for calculating coordinates. For example, in the code below, the <em>draggable</em> element moves itself to the mouse cursor!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70705ce4985c88903c9c1e2075e52458/href">https://medium.com/media/70705ce4985c88903c9c1e2075e52458/href</a></iframe><p>Here we have created an element and its screenshot. But we are only interested in the screenshot, so the element must be hidden. We can’t use <em>display:none</em> or zero <em>opacity</em> to hide it, because those styles will extend to our screenshot as well. Therefore, we use the following hack:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c0af56d1e57429147865a0476f94bc2/href">https://medium.com/media/2c0af56d1e57429147865a0476f94bc2/href</a></iframe><p>And do not forget to delete the created element at the end of the drag:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18321649536b07ea21dbac6b37e415f4/href">https://medium.com/media/18321649536b07ea21dbac6b37e415f4/href</a></iframe><p>Let’s see what happens.</p><figure><img alt="The draggable element moves to the mouse cursor." src="https://cdn-images-1.medium.com/max/512/1*AjA090ws0ZnakI13HqwjPQ.gif" /><figcaption>The <em>draggable</em> element moves to the mouse cursor</figcaption></figure><p>So cute!</p><p>In fact, this is a necessary measure — in real conditions, native DnD just does not look very nice, creating an image with all the hovers, shadows and the surrounding environment.</p><p><strong>DnD for other places!</strong></p><p>With the help of drag &amp; drop you can implement a lot of interesting things. You are only limited by your imagination.</p><p>For example, the code below removes items when dragging them to the trash can:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4a3bd08d51fb998c299a424736185d6/href">https://medium.com/media/d4a3bd08d51fb998c299a424736185d6/href</a></iframe><p><em>onDrop</em> handler:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/661c8766fca8d274580d042b1cfbaba0/href">https://medium.com/media/661c8766fca8d274580d042b1cfbaba0/href</a></iframe><p>And here we go!</p><figure><img alt="Throw items into the trash." src="https://cdn-images-1.medium.com/max/512/1*-7OvHxpeNAgSZVGVYwsySg.gif" /><figcaption>Throw items into the trash</figcaption></figure><p><strong>DnD for everything!</strong></p><p>Still not enough? We can do more! Much more!</p><p>For the next point, we will again expand the functionality a bit by adding handling for cases when the user drags a <em>file</em> or <em>text</em>. To do this, let’s turn to <a href="https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer">dataTransfer</a> again, now the <em>onDrop</em> event.</p><p>To check whether there are files inside whatever the user is dragging, we will do this:</p><blockquote>if (e.dataTransfer.types.filter(i =&gt; i === ‘Files’).length) {…}</blockquote><p>But you can also drag and drop text. And it also has its own processing, like:</p><blockquote>if (e.dataTransfer.types.filter(i =&gt; i === ‘text/plain’).length) {…}</blockquote><p>In both cases, we check for the presence of the desired type in the dragged elements in order to process them.</p><p>In the end, our handler will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11076480d587b94f3aec9e7a05218cca/href">https://medium.com/media/11076480d587b94f3aec9e7a05218cca/href</a></iframe><p>And, of course, the result:</p><figure><img alt="Selected a text and dragged it into the list." src="https://cdn-images-1.medium.com/max/512/1*u940a6YDL2YnYkAj2Uf0jQ.gif" /><figcaption>Drag &amp; drop text</figcaption></figure><figure><img alt="Took a file and dropped it into the list." src="https://cdn-images-1.medium.com/max/512/1*GqT5Zs1wzu6uCoiNuX53mA.gif" /><figcaption>Drag &amp; drop files</figcaption></figure><p><a href="https://codepen.io/-vladimir-intspirit-/pen/eYVVrbx">Here</a> you can try it yourself!</p><p>When adding React Redux, the described functionality is enough to cover 98% of the tasks, and it will allow you to start a real DnD party!</p><figure><img alt="A cat is shocked about so much DnD." src="https://cdn-images-1.medium.com/max/512/1*APyk_7ng9edTUFhN19GbnA.jpeg" /></figure><p><strong>About us</strong></p><p><a href="https://intspirit.com/">Intspirit</a> is an outsource company focused on developing complex web and mobile apps. We are in love with coding and widely share our knowledge.</p><blockquote>Follow us on <a href="https://intspirit.medium.com/">Medium</a> to not miss new articles.</blockquote><blockquote>Follow us on <a href="https://www.linkedin.com/company/intspirit/">LinkedIn</a> and <a href="https://www.facebook.com/Intspirit/">Facebook</a> to be aware of other awesome projects we do.</blockquote><blockquote>Try yourself in our <a href="https://t.me/intspirit">telegram-channel</a> with JS quizzes frequently asked in job interviews.</blockquote><p>Thank you for reading, and let’s make IT better!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4a6ce4b850e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From React to React Native, or There and Back]]></title>
            <link>https://intspirit.medium.com/from-react-to-react-native-or-there-and-back-6768273c0d6f?source=rss-5e5426eda6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6768273c0d6f</guid>
            <dc:creator><![CDATA[Intspirit Ltd]]></dc:creator>
            <pubDate>Thu, 12 May 2022 07:39:58 GMT</pubDate>
            <atom:updated>2022-05-12T07:39:58.904Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mobile development through the eyes of a web developer</h4><figure><img alt="React + Native code = React Native" src="https://cdn-images-1.medium.com/max/369/1*pWWjx_08zKLF7OIcMH9QSg.png" /></figure><p>In this article, I will talk about how I ended up working on a mobile application project despite only having experience in web development. What’s inside? — the difficulties encountered, mistakes made and tips on how you could protect yourself from repeating them.</p><p><strong>Intro</strong></p><p>I wanted to give <a href="https://reactnative.dev/">React native</a> a try for a long time, especially because I assumed that it’s just a <a href="https://reactjs.org/">React</a> but extremely tailored for mobiles. But there was never enough time. And here I was presented with just the perfect opportunity!</p><p>It started like the Hobbit’s journey…</p><p><strong>Expo vs React Native</strong></p><p>At the start of a React Native project you have 2 options: <a href="https://reactnative.dev/docs/environment-setup">React Native CLI and Expo CLI</a>. Both will make you work with React native, and the only meaningful difference is that if you create an app using React Native CLI you can change the native code (<a href="https://www.java.com/ru/">Java</a>/<a href="https://kotlinlang.org/">Kotlin</a>/<a href="https://developer.apple.com/swift/">Swift</a>/<a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html">Objective C</a>).</p><p>Initially, the project that I had to work on was supposed to be a very simple application for presenting &amp; viewing information in the format of cards/tabs/tables. Therefore, we opted for Expo. Mainly due to simplicity, not needing to dig into the native part of the application, and the ability to limit ourselves to React (Native) components. Another significant advantage of Expo is that it is easier to update apps in stores compared to React Native (<a href="https://play.google.com/store">Play Market</a>/<a href="https://www.apple.com/app-store/">App Store</a>). And in case you need to expand the functionality, it is possible to migrate from Expo to React Native, allowing you to access the native part of the application — for example, <a href="https://webrtc.org/">WebRTC</a>.</p><p><strong>How to use Expo</strong></p><p>Install Expo CLI:</p><p><strong>npm install --global expo-cli</strong></p><p>To create an application using the Expo CLI, use this command:</p><p><strong>expo init app-name</strong></p><p>To run the application, use the following command:</p><p><strong>expo start</strong></p><p>The easiest way to run apps on iOS/Android devices is to use the <a href="https://expo.dev/client">Expo Go</a> app. With Expo Go you won’t even need a MacOS to run your app on iOS.</p><p>When you run <em>expo start</em>, Expo CLI starts a <a href="https://facebook.github.io/metro/">Metro Bundler</a>, which is an HTTP server that compiles the JavaScript code of the app and serves it to the Expo Go app on your device (<em>Note that your computer &amp; mobile device have to be on the same WiFi network</em>). When you update your code, Expo Go will reload your app automatically.</p><p>There are two approaches to building applications with Expo: <em>managed</em> and <em>bare</em> workflows.</p><p><em>Managed Workflow</em> makes building applications as simple as possible. This approach doesn’t require much use of <a href="https://developer.apple.com/xcode/">Xcode</a> or <a href="https://developer.android.com/studio">Android Studio</a> (although they are useful for debugging!) — you mostly write JavaScript code and manage configuration such as app icon and splash screen, using <a href="https://docs.expo.dev/workflow/configuration/">app.json/app.config.js</a> or <a href="https://docs.expo.dev/guides/config-plugins/">Config Plugins</a>. Expo SDK provides an increasingly comprehensive set of APIs that allows access to mobile device’s resources such as camera, biometric authentication, file system, haptics, etc. Applications that use the Expo CLI to run on the device are Managed Workflow apps.</p><p><em>Bare workflow</em> allows you to modify the native part of the application and provides the same set of APIs as Managed Workflow, but without the help of Expo. To run Bare workflow applications you use <em>yarn ios</em> and <em>yarn android</em> commands to start the JavaScript bundler server and build the project binary. This requires Xcode or Android Studio, depending on the platform. Apps built with React Native CLI are Bare Workflow apps.</p><p>Unfortunately (or fortunately, depending how you look at it hehe!), with the growth of the project each developer wonders if, maybe, you don’t even need Expo in terms of Managed workflow? And I think that’s true.</p><p>Expo provides an opportunity to migrate from Managed workflow to Bare workflow. To do this, you need to run the <em>expo eject</em> command. This command will turn your application into a pure React Native application, leaving only those Expo SDK APIs that you have already used in the project. To add another Expo SDK library, you can use <em>expo install</em>.</p><p><strong>And that’s where the problems begin</strong></p><p>In my case, the transition to Bare workflow happened on its own and I did not notice it happening. However, since this transition went smoothly, I continued to work with my application as if it was still a Managed Workflow application, i.e. the “.apk” was built and launched using Expo tools.</p><p>The problems started suddenly when it had become necessary to use WebRTC technologies in the project — <a href="https://marketplace.zoom.us/docs/sdk/native-sdks/introduction/">Zoom SDK</a>, to be specific. And then something like “Mordor: a guide for Hobbits” began — after going through a bunch of texts and a huge number of forums and articles, I got the impression that I came to React Native so as not to use it. Because the development process was really slow.</p><p>And then, after unsuccessfully stumbling around, I fell &amp; woke up with a cast formed of Java/Kotlin &amp; Swift/Objective C (remove the one you don’t like).</p><figure><img alt="Went to ReactNative because of JavaScript — learnt Objective-C and Java." src="https://cdn-images-1.medium.com/max/512/1*hvRif_ckaeXERImQuCLcwA.png" /></figure><p>Omitting the chilling details of diving into the world of Java and Swift, I can only say that the necessary functions were written, but then the realization came… When starting and even building the application, I cannot access the written functions that have access to the native part of the application (Zoom SDK in particular). Having bogged down in a ton of documentation, I nevertheless solved the problem. But at what cost? I had to forget about <a href="https://code.visualstudio.com/">VS Code</a> for some time, alternating between Android Studio and XCode. At the same time, testing and debugging involved either use of an emulator or building and installing the application on the device. The only consolation was the fact that it already looked and felt like mobile development (Although, I myself was not very mobile during these times. Looks like I still got deceived somewhere).</p><p><strong>React vs React Native</strong></p><p>But back to React Native: as you guessed it, the journey did not just take 20 minutes.</p><figure><img alt="React Native — a journey for 20 minutes" src="https://cdn-images-1.medium.com/max/444/1*ObURTmGbAn9qdBjTIheqDw.png" /></figure><p>Initially, I thought that React Native is the same React, only Native. After a fairly long period of time, I can say that I was not so far from the truth.</p><p>Do you have problems with semantic layouts and do everything on divs instead? You can’t live without hooks inside other hooks? Your PM is beating you with a stick for your inline styles, but you still keep using them regardless?</p><p>Then React Native is for you!</p><p>Here you can write the entire application using View-components, the same hooks and even more — there is no CSS here! Which almost justifies your self-expression with inline-styles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29ca861e9485c564f17ca7caf3f5133e/href">https://medium.com/media/29ca861e9485c564f17ca7caf3f5133e/href</a></iframe><p><strong>Some wonderful React Native’s peculiarities</strong></p><p>1. By default, all elements are laid out as flex-column, unlike the browser, where by default <em>display:flex</em> sets the elements as a row.</p><p>2. In some cases Android and iOS components are rendered differently. For example, calendar and switch. Therefore, if you need to follow the design, you will have to use your own custom components.</p><figure><img alt="Switch as an example of platform specific components." src="https://cdn-images-1.medium.com/max/512/1*nArI6guGZfiL1XVFYPNwSA.png" /><figcaption>Switch — a platform specific component.</figcaption></figure><p>3. Another noteworthy feature is the animation. In the browser, to simplify, it all comes down to <em>keyframe</em>, <em>transition</em> and <em>transform</em>. In the case of React Native, however, everything starts shining with new, never before experienced colors of pain. In general, this looks like a keyframe with provided values and animation times.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16172c51702784878eca73f0e65271c4/href">https://medium.com/media/16172c51702784878eca73f0e65271c4/href</a></iframe><p>“Animated” provides three types of animation. Each animation type provides a specific animation curve that controls how your values animate from their start value to their end value:</p><ul><li><a href="https://reactnative.dev/docs/animated#decay">Animated.decay()</a> starts at initial speed and gradually decelerates to a complete stop.</li><li><a href="https://reactnative.dev/docs/animated#spring">Animated.spring()</a> provides a basic physical model of a spring.</li><li><a href="https://reactnative.dev/docs/animated#timing">Animated.timing()</a> animates a value over time with <a href="https://reactnative.dev/docs/easing">easing functions</a>.</li></ul><p>In most cases, you will use “timing()”. The default is a symmetrical easyInOut curve that conveys a gradual acceleration of the object to full speed and ends with a gradual deceleration to a complete stop.</p><p>4. React Native allows you to render existing sites using a WebView, i.e. a React Native app can play the role of a browser. In my case, I used this method to render the service available on the web version with full functionality in order to save time and not reinvent the wheel.</p><figure><img alt="I heard you like React. So I put React in your react Native webview so you can react while you react." src="https://cdn-images-1.medium.com/max/512/1*2_W_dNn20jGdQPJibSbs0Q.png" /></figure><p>At the moment, WebView is a component of a third-party library, however, it’s too useful not to talk about it.</p><p>In general, it has something similar to <a href="https://www.w3schools.com/tags/tag_iframe.asp">iframe</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c327a415e9ea0456804e0eac4b7bbb55/href">https://medium.com/media/c327a415e9ea0456804e0eac4b7bbb55/href</a></iframe><p>5. Moving away from the topic of React Native and touching on the topic of mobile development in general, I should mention the features of working with the <a href="https://en.wikipedia.org/wiki/Google_APIs">Google API</a>.</p><p>When working through Expo, you must specify separate keys for the application in the Expo ecosystem and for the standalone application (the name says it all — this is an application that is no longer limited to the Expo ecosystem and exists on its own). In addition, you need to create separate keys for <em>iOS</em> and <em>Android</em>. So, you need at least 2 keys to publish and build your app, but if you don’t want to give up on Expo then the number of keys goes up to 4 (Never laugh at live dragons!).</p><p>Summing up, I would like to say that React Native has a large community. And even if support for some of the features the community likes (such as the checkbox for iOS) ceases to exist, some especially active developers are very quickly expanding the npm base and adding the necessary solutions.</p><p><strong>In conclusion</strong></p><p>Should you try React Native if you have experience with React (or even if you don’t)?</p><p>In my opinion it’s definitely worth it, but (and it’s a big “but”) if you are faced with the prospect of creating a large and complex application you better get to learning Java/Kotlin/Swift/ObjectiveC, because sooner or later you will have to encounter Smaug sleeping on the gold the native part. And then you won’t get by with just a React Native.<br> “Go back? No good at all! Go sideways? Impossible! Go forward? Only thing to do! On we go!” More interesting articles soon, <a href="https://intspirit.medium.com/">follow</a> &amp; clap here at the Intspirit’s blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6768273c0d6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Networks: the best open-source library for object detection & classification]]></title>
            <link>https://intspirit.medium.com/neural-networks-the-best-open-source-library-for-object-detection-classification-ad99bcc073a9?source=rss-5e5426eda6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad99bcc073a9</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[object-classification]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Intspirit Ltd]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 10:12:37 GMT</pubDate>
            <atom:updated>2022-04-06T10:12:37.019Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="http://intspirit.com/">Intspirit</a>/<a href="https://intspirit.medium.com/neural-networks-start-with-basics-and-stay-for-more-867e66fc4638">Neural Networks: basics</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*825CSKV-TFyZvPXP" /></figure><p>In the previous article, we showed a way <a href="https://intspirit.medium.com/neural-networks-start-with-basics-and-stay-for-more-867e66fc4638">how to start diving into the amazing world of neural networks</a>. But what if you, for some reason, don’t have either time or resources to build and train your own neural network? Well, neural networks are a rapidly developing field, and with “googling a lot” you can find wonderful open-source solutions for almost any task. Let’s pull back the Neural curtain and help you to solve it by using a good open-source solution in this article.</p><p><strong>ImageAI</strong></p><p><a href="https://github.com/OlafenwaMoses/ImageAI">ImageAI</a> is an open source Python library by <a href="https://ng.linkedin.com/in/moses-olafenwa-6b191a59">Moses Olafenwa</a> written for finding and classifying objects across videos and images. But what exactly makes it so cool? The library can work with already trained models, using which you can recognize 80 different kinds of objects and classify over 1000.</p><p>As you will soon see, in order to recognize or classify objects in a video or image, you need no more than 10 lines of code. This library also allows you to train your own model to recognize the specific objects you need.</p><p><strong>Object Detection</strong></p><p>Fig.1 shows the objects that you can recognize with ImageAI according to its <a href="https://github.com/OlafenwaMoses/ImageAIDocumentation/blob/master/detection/index.rst">documentation</a>:</p><figure><img alt="Objects that can be detected on image or video using ImageAI library: person, dog, boat, car, umbrella, etc." src="https://cdn-images-1.medium.com/max/1024/0*FbcC0c2HnRl9GCk_" /><figcaption>Fig.1 Objects that can be detected on image or video using ImageAI library.</figcaption></figure><p>For Object Recognition, you can use one of the three pre-trained models that the library can work with: RetinaNet, YOLOv3, and TinyYOLOv3. These models are already trained to recognize certain objects using large training datasets. Each of these models has its own pros and cons. You can choose the model that best suits your application, or use your own model. We will cover training your own model in the next article, but for now let’s take a closer look at the standard models that ImageAI can work with:</p><ol><li><strong>RetinaNet</strong> is one of the best one-stage Object Detection models that has proven to work well with dense and small scale objects. For this reason, it has become a popular object detection model to be used with aerial and satellite imagery.</li><li><strong>YOLO</strong> (You Only Look Once) is one of the most popular series of Object Detection models. Its advantage has been in providing real-time detections while approaching the accuracy of state-of-the-art object detection models. For more information on how it works under the hood, click <a href="https://developers.arcgis.com/python/guide/yolov3-object-detector/">here</a>.</li><li><strong>TinyYOLOv3</strong> is another version of the YOLOv3 model. It has a much higher Object Recognition speed (about 442% faster than other YOLO variants), but lower detection accuracy.</li></ol><p><strong>How to detect objects using ImageAI</strong></p><p>First things, you need to decide which model you want to use, and download it. We will put the path to the model in our program. The models can be downloaded using the links below:</p><p><a href="https://github.com/OlafenwaMoses/ImageAI/releases/download/essentials-v5/resnet50_coco_best_v2.1.0.h5/">Download RetinaNet Model — resnet50_coco_best_v2.1.0.h5</a><br><a href="https://github.com/OlafenwaMoses/ImageAI/releases/download/1.0/yolo.h5/">Download YOLOv3 Model — yolo.h5<br></a><a href="https://github.com/OlafenwaMoses/ImageAI/releases/download/1.0/yolo-tiny.h5/">Download TinyYOLOv3 Model — yolo-tiny.h5</a></p><p>To detect objects in any image or video file using pre-trained models, ImageAI provides the ObjectDetection class.</p><p><strong>Image Object Detection</strong></p><p>To find objects in the image, we only need 7 lines of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fef70875274e017afefb0f09cf521172/href">https://medium.com/media/fef70875274e017afefb0f09cf521172/href</a></iframe><p>After executing this code, the detections variable will contain an array of objects, each containing:</p><ul><li>name (string)</li><li>percentage_probability (float)</li><li>box_points (list of x1,y1,x2 and y2 coordinates)</li></ul><p>As well as an image with the found objects being highlighted with squares and signed:</p><figure><img alt="Result of image object detection: the source image with the found objects being highlighted with squares and signed with names and coordinates" src="https://cdn-images-1.medium.com/max/768/0*9HUWVM9mG6Az23Y_" /><figcaption><a href="https://imageai.readthedocs.io/en/latest/_images/image1.jpg">Fig. 2 — Result of <strong>Object Detection </strong>using ImageAI</a></figcaption></figure><p><strong>Video Object Detection</strong></p><p>To detect objects in a video, create an instance of the <strong>ObjectDetection</strong> class and select a model in the same way as for detecting objects in an image. Then use the <strong>detectObjectsFromVideo</strong> method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a42344722352cac09d8d41de3276305/href">https://medium.com/media/5a42344722352cac09d8d41de3276305/href</a></iframe><p>Besides <strong>per_second_function </strong>and<strong> video_complete_function </strong>the method can accept other functions that are triggered when processing a certain section of the video. Here is their complete list:</p><p>- <strong>per_frame_function</strong> — triggers once a frame is processed<br>- <strong>per_second_function</strong> —<strong> </strong>triggers once a second is processed<br>- <strong>per_minute_function </strong>— triggers once a minute is processed<br>- <strong>video_complete_function</strong> — triggers once the entire video is processed</p><p>The functions above can be useful for getting parts of the result in stages before the processing is finished:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7e3c97350676bff7301a26a0f7958a2/href">https://medium.com/media/a7e3c97350676bff7301a26a0f7958a2/href</a></iframe><p>It is recommended to pass the correct value as frames_per_second. You can get this value using the <a href="https://pypi.org/project/opencv-python/">cv2</a> library:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cdc32707c42f7b7512bd8e42e532620/href">https://medium.com/media/2cdc32707c42f7b7512bd8e42e532620/href</a></iframe><p>The fps variable will contain the frames per second of your video file.</p><p>Be careful when trying to recognize objects in a longer video, as the library does not allow to programmatically interrupt this process. An issue regarding this has been opened, but not answered yet:</p><p><a href="https://github.com/OlafenwaMoses/ImageAI/issues/637">https://github.com/OlafenwaMoses/ImageAI/issues/637</a></p><p><strong>Object Classification</strong></p><p>To classify objects, you can use one of the four pre-trained models that the library can work with: <a href="https://ai.googleblog.com/2018/04/mobilenetv2-next-generation-of-on.html">MobileNetV2</a>, <a href="https://iq.opengenus.org/resnet50-architecture/">ResNet50</a>, <a href="https://www.kaggle.com/datasets/google-brain/inception-v3">InceptionV3</a> and <a href="https://keras.io/api/applications/densenet/">DenseNet121</a>. These models have been trained on the ImageNet-1000 dataset and can recognize up to 1000 different objects in an image. Let’s take a closer look at each of them.</p><ol><li><strong>MobileNetV2</strong> is a convolutional neural network architecture that seeks to perform well on mobile devices. MobileNets support any input size greater than 32x32, with larger image sizes offering better performance.</li><li><strong>ResNet-50</strong> model is a convolutional neural network (CNN) that is 50 layers deep. In a typical convolutional neural network, several layers are stacked on top of each other, with each layer learning features from the output of the preceding layer. However, the ResNet50 model uses residual learning, where instead of the features from the input being learnt, the residuals (the features learned subtracted from the input), are learnt, taking care of the issue of degrading accuracy.</li><li><strong>InceptionV3</strong> is a widely-used image recognition model that has been shown to attain greater than 78.1% accuracy on the ImageNet dataset. For maximum accuracy, images should be 299x299x3 pixels in size.</li><li><strong>DenseNet121</strong> — Dense Convolutional Network (DenseNet) connects each layer to every other layer in a feed-forward fashion. DenseNets have several advantages: they alleviate the vanishing-gradient problem, strengthen feature propagation, encourage feature reuse, and substantially reduce the number of parameters. The required minimum input size of the model is 29x29.</li></ol><figure><img alt="How to confuse Machine Learning: dog or muffin?" src="https://cdn-images-1.medium.com/max/724/0*WHC2zR7aqNpbx5Nl" /><figcaption><a href="https://ichi.pro/ru/memy-masinnogo-obucenia-lgut-vam-matematiceskoe-issledovanie-207498147306826">Fig. 3 Dog or muffin?</a></figcaption></figure><p><strong>How to classify objects using ImageAI</strong></p><p>Once again, first you need to decide which model you want to use, and download it. We will put the path to the model in our program. The models can be downloaded using the links below:</p><p><a href="https://github.com/OlafenwaMoses/ImageAI/releases/download/essentials-v5/mobilenet_v2.h5/">Download MobileNetV2 Model</a><br><a href="https://github.com/OlafenwaMoses/ImageAI/releases/download/essentials-v5/resnet50_imagenet_tf.2.0.h5/">Download ResNet50 Model</a><br><a href="https://github.com/OlafenwaMoses/ImageAI/releases/download/1.0/inception_v3_weights_tf_dim_ordering_tf_kernels.h5/">Download InceptionV3 Model</a><br><a href="https://github.com/OlafenwaMoses/ImageAI/releases/download/1.0/DenseNet-BC-121-32.h5/">Download DenseNet121 Model</a></p><p>To classify objects in an image, use the <strong>ImageClassification</strong> class, as shown in this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a67f3d33645160ad73273797cf2efd5/href">https://medium.com/media/1a67f3d33645160ad73273797cf2efd5/href</a></iframe><p>Not that hard, right?</p><p>In the next article, we’ll describe how to train your own model using ImageAI and write an Angular interface for preparing data for training.</p><blockquote>Subscribe, so you don’t miss out!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad99bcc073a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>