<?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 Tom on Medium]]></title>
        <description><![CDATA[Stories by Tom on Medium]]></description>
        <link>https://medium.com/@tom-cat?source=rss-96bf7d1fdcfa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C1DCkYObdLtKtMWoY_V6kA.jpeg</url>
            <title>Stories by Tom on Medium</title>
            <link>https://medium.com/@tom-cat?source=rss-96bf7d1fdcfa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:43:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tom-cat/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[3 Scenarios Where You Shouldn’t Use Arrow Functions]]></title>
            <link>https://javascript.plainenglish.io/3-scenarios-where-you-shouldnt-use-arrow-functions-862388acd05d?source=rss-96bf7d1fdcfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/862388acd05d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Thu, 27 Jan 2022 16:04:11 GMT</pubDate>
            <atom:updated>2022-01-27T16:04:11.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sN8TkWijx4N9ZVzC" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Compared with ordinary functions (declared with the function keyword), arrow functions have many differences, including:</p><ul><li>An arrow function doesn’t have its own <a href="https://www.javascripttutorial.net/javascript-this/">this</a> value</li><li>It doesn’t have the arguments object.</li><li>It doesn’t have the [[construct]] internal slot.</li></ul><p>Here are 3 scenarios where arrow functions should not be used.</p><h3>1. Defining methods on an object</h3><p>In JavaScript, the method is a function stored in a property of an object. When calling the method, this becomes the object that the method belongs to.</p><h4>1a. Object literal</h4><p>Since the arrow function has a short syntax, it’s inviting to use it for a method definition. Let’s take a try:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/382926e40ad699daf7007b361e686658/href">https://medium.com/media/382926e40ad699daf7007b361e686658/href</a></iframe><p>calculate.sum method is defined with an arrow function. But on invocation calculate.sum() throws a TypeError, because this.array is evaluated to undefined.<br>When invoking the method sum() on the calculate object, the context remains window. It happens because the arrow function binds the context lexically with the window object.<br>Executing this.array is equivalent to window.array, which is undefined.</p><p>The solution is to use a function expression or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">shorthand syntax</a> for method definition (available in ECMAScript 6). In such a case this is determined by the invocation, but not by the enclosing context. Let&#39;s see the fixed version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80804ce98204bd6e7e2cdc71bfae9ba6/href">https://medium.com/media/80804ce98204bd6e7e2cdc71bfae9ba6/href</a></iframe><p>Because sum is a regular function, this on invocation of calculate.sum() is the calculate object. this.array is the array reference, therefore the sum of elements is calculated correctly: 6.</p><h4>1b. Object prototype</h4><p>The same rule applies when defining methods on a prototype object.<br>Instead of using an arrow function for defining sayCatName method, which brings an incorrect context window:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6830affd1ed96aef3453075818c8df59/href">https://medium.com/media/6830affd1ed96aef3453075818c8df59/href</a></iframe><p>use the <em>old school</em> function expression:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/499b7da9dda46fbe551bea1a3b812930/href">https://medium.com/media/499b7da9dda46fbe551bea1a3b812930/href</a></iframe><h3>2. Callback functions with dynamic context</h3><p>this in JavaScript is a powerful feature. It allows changing the context depending on the way a function is called. Frequently the context is the target object on which invocation happens, making the code more <em>natural</em>. It says like &quot;something is happening with this object&quot;.</p><p>However, the arrow function binds the context statically on the declaration and is not possible to make it dynamic. It’s the other side of the medal in a situation when lexical this is not necessary.</p><p>Attaching event listeners to DOM elements is a common task in client-side programming. An event triggers the handler function with this as the target element. Handy usage of the dynamic context.</p><p>The following example is trying to use an arrow function for such a handler:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10e22d5b2058b0849a86ed2a94b785ce/href">https://medium.com/media/10e22d5b2058b0849a86ed2a94b785ce/href</a></iframe><p>this is window in an arrow function that is defined in the global context. When a click event happens, the browser tries to invoke the handler function with button context, but the arrow function does not change its pre-defined context.</p><p>this.innerHTML is equivalent to window.innerHTML and has no sense.</p><p>You have to apply a function expression, which allows changing this depending on the target element:</p><pre>const button = document.getElementById(&#39;myButton&#39;);<br>button.addEventListener(&#39;click&#39;, function() {<br>  console.log(this === button); // =&gt; true<br>  this.innerHTML = &#39;Clicked button&#39;;<br>});</pre><p>When the user clicks the button, this in the handler function is button. Thus this.innerHTML = &#39;Clicked button&#39; modifies correctly the button text to reflect clicked status.</p><h3>3. Invoking constructors</h3><p>this in a construction invocation is the newly created object. When executing new MyFunction(), the context of the constructor MyFunction is a new object: this instanceof MyFunction === true.</p><p>Notice that an arrow function cannot be used as a constructor. JavaScript implicitly prevents doing that by throwing an exception.</p><p>Anyway this is setup from the enclosing context and is not the newly created object. In other words, an arrow function constructor invocation doesn&#39;t make sense and is ambiguous.</p><p>Let&#39;s see what happens if however trying to:</p><pre>const Message = (text) =&gt; {<br>  this.text = text;<br>};<br>// Throws &quot;TypeError: Message is not a constructor&quot;<br>const helloMessage = new Message(&#39;Hello World!&#39;);</pre><p>Executing new Message(&#39;Hello World!&#39;), where Message is an arrow function, JavaScript throws a TypeError that Message cannot be used as a constructor.</p><p>I consider it an efficient practice that ECMAScript 6 fails with verbose error messages in such situations. Contrary to <em>fail silently</em> specific to previous JavaScript versions.</p><p>The above example is fixed using a <a href="https://developer.mozilla.org/en/docs/web/JavaScript/Reference/Operators/function">function expression</a>, which is the correct way (including the <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/function">function declaration</a>) to create constructors:</p><pre>const Message = function(text) {<br>  this.text = text;<br>};<br>const helloMessage = new Message(&#39;Hello World!&#39;);<br>console.log(helloMessage.text); // =&gt; &#39;Hello World!&#39;</pre><h3>Too short syntax</h3><p>The arrow function has a nice property of omitting the arguments parenthesis (), block curly brackets {} and return if the function body has one statement. This helps in writing very short functions.</p><p>My university professor of programming gives students an interesting task: write the shortest function that counts the string length in C language. This is a good approach to study and explore a new language.</p><p>Nevertheless, in real-world applications, the code is read by many developers. The shortest syntax is not always appropriate to help your colleague understand the function on the fly.</p><p>At some level, the compressed function becomes difficult to read, so try not to get into a passion. Let’s see an example:</p><pre>const multiply = (a, b) =&gt; b === undefined ? b =&gt; a * b : a * b;<br>const double = multiply(2);<br>double(3);      // =&gt; 6<br>multiply(2, 3); // =&gt; 6</pre><p>multiply returns the multiplication result of two numbers or a closure tied with first parameter for later multiplication.</p><p>The function works nice and looks short. But it may be tough to understand what it does from the first look.</p><p>To make it more readable, it is possible to restore the optional curly braces and return statement from the arrow function or use a regular function:</p><pre>function multiply(a, b) {<br>  if (b === undefined) {<br>    return function(b) {<br>      return a * b;<br>    }<br>  }<br>  return a * b;<br>}<br>const double = multiply(2);<br>double(3);      // =&gt; 6<br>multiply(2, 3); // =&gt; 6</pre><p>It is good to find a balance between short and verbose to make your JavaScript straightforward.</p><h3>Conclusion</h3><p>Without a doubt, the arrow function is a great addition. When used correctly it brings simplicity in places where earlier you had to use .bind() or try to catch the context. It also makes the code lighter.</p><p>Advantages in some situations bring disadvantages in others. You can’t use an arrow function when a dynamic context is required: defining methods, creating objects with constructors, getting the target from this when handling events.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=862388acd05d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/3-scenarios-where-you-shouldnt-use-arrow-functions-862388acd05d">3 Scenarios Where You Shouldn’t Use Arrow Functions</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[The Differences Between Arrow and Regular Functions You Should Know]]></title>
            <link>https://javascript.plainenglish.io/the-differences-between-arrow-and-regular-functions-you-should-know-401c4bf22ad3?source=rss-96bf7d1fdcfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/401c4bf22ad3</guid>
            <category><![CDATA[arrow-functions]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Thu, 02 Jul 2020 15:19:51 GMT</pubDate>
            <atom:updated>2020-07-02T15:19:51.090Z</atom:updated>
            <content:encoded><![CDATA[<h4>They’re both useful, but don’t confuse them</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xsl5pg7A7jVHZcUm" /><figcaption>Photo by <a href="https://unsplash.com/@hishahadat?utm_source=medium&amp;utm_medium=referral">Shahadat Rahman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In JavaScript, you can define functions in many ways.</p><p>The first, usual way, is by using the function keyword:</p><pre>// Function declaration<br>function greet(who) {<br>  return `Hello, ${who}!`;<br>}</pre><pre>// Function expression<br>const greet = function(who) {<br>  return `Hello, ${who}`;<br>}</pre><p>The function declaration and function expression I’m going to reference as a <em>regular function</em>.</p><p>The second way, available starting ES2015, is the <em>arrow function</em> syntax:</p><pre>const greet = (who) =&gt; {<br>  return `Hello, ${who}!`;<br>}</pre><p>While both the regular and arrow syntaxes define functions, when would you choose one instead of another? That’s a good question.</p><p>In this post, I’m going to show the main differences between the two, so you could choose the right syntax for your needs.</p><h3>1. this value</h3><h4>1.1 Regular function</h4><p>Inside of a regular JavaScript function, this value (aka the execution context) is dynamic.</p><p>The dynamic context means that the value of this depends on how the function is invoked. In JavaScript, there are 4 ways you can invoke a regular function.</p><p>During a <em>simple invocation</em> the value of this equals to the global object (or undefined if the function runs in strict mode):</p><pre>function myFunction() {<br>  console.log(this);<br>}</pre><pre>// Simple invocation<br>myFunction(); // logs global object (window)</pre><p>During a <em>method invocation</em> the value of this is the object owning the method:</p><pre>const myObject = {<br>  method() {<br>    console.log(this);<br>  }<br>};<br>// Method invocation<br>myObject.method(); // logs myObject</pre><p>During an <em>indirect invocation</em> using myFunc.call(thisVal, arg1, ..., argN) or myFunc.apply(thisVal, [arg1, ..., argN]) the value of this equals to the first argument:</p><pre>function myFunction() {<br>  console.log(this);<br>}</pre><pre>const myContext = { value: &#39;A&#39; };</pre><pre>myFunction.call(myContext);  // logs { value: &#39;A&#39; }<br>myFunction.apply(myContext); // logs { value: &#39;A&#39; }</pre><p>During a <em>constructor invocation</em> using new keyword this equals to the newly created instance:</p><pre>function MyFunction() {<br>  console.log(this);<br>}</pre><pre>new MyFunction(); // logs an instance of MyFunction</pre><h4>1.2 Arrow function</h4><p>The behavior of this inside of an arrow function differs considerably from the regular function’s this behavior.</p><p>No matter how or where being executed, this value inside of an arrow function always equals this value from the outer function. In other words, the arrow function resolves this lexically. In another words, the arrow function doesn’t define its own execution context.</p><p>In the following example, myMethod() is an outer function of callback() arrow function:</p><pre>const myObject = {<br>  myMethod(items) {<br>    console.log(this); // logs myObject    const callback = () =&gt; {<br>      console.log(this); // logs myObject    };<br>    items.forEach(callback);<br>  }<br>};</pre><pre>myObject.myMethod([1, 2, 3]);</pre><p>this value inside the arrow function callback() equals to this of the outer function myMethod().</p><p>this resolved lexically is one of the great features of arrow functions. When using callbacks inside methods you are sure the arrow function doesn’t define its own this: no more const self = this or callback.bind(this) workarounds.</p><p>Contrary to a regular function, the indirect invocation of an arrow function using myArrowFunc.call(thisVal) or myArrowFunc.apply(thisVal) doesn’t change the value of this: the context value is always resolved lexically.</p><h3>2. Constructors</h3><h4>2.1 Regular function</h4><p>As seen in the previous section, the regular function can easily construct objects.</p><p>For example, the Car() function creates instances of a car:</p><pre>function Car(color) {<br>  this.color = color;<br>}</pre><pre>const redCar = new Car(&#39;red&#39;);<br>redCar instanceof Car; // =&gt; true</pre><p>Car is a regular function, and when invoked with new keyword, it creates new instances of Car type.</p><h4>2.2 Arrow function</h4><p>A consequence of this resolved lexically is that an arrow function cannot be used as a constructor.</p><p>If you try to invoke an arrow function prefixed with new keyword, JavaScrip throws an error:</p><pre>const Car = (color) =&gt; {<br>  this.color = color;<br>};</pre><pre>const redCar = new Car(&#39;red&#39;); // TypeError: Car is not a constructor</pre><p>Invoking new Car(&#39;red&#39;), where Car is an arrow function, throws TypeError: Car is not a constructor.</p><h3>3. arguments object</h3><h4>3.1 Regular function</h4><p>Inside the body of a regular function, arguments is a special array-like object containing the list of arguments with which the function has been invoked.</p><p>Let’s invoke myFunction function with 2 arguments:</p><pre>function myFunction() {<br>  console.log(arguments);<br>}</pre><pre>myFunction(&#39;a&#39;, &#39;b&#39;); // logs { 0: &#39;a&#39;, 1: &#39;b&#39;}</pre><p>arguments array-like object contains the invocation arguments: &#39;a&#39; and &#39;b&#39;.</p><h4>3.2 Arrow function</h4><p>On the other side, no arguments special keyword is defined inside an arrow function.</p><p>Again (same as with this value), the arguments object is resolved lexically: the arrow function accesses arguments from the outer function.</p><p>Let’s try to access arguments inside of an arrow function:</p><pre>function myRegularFunction() {<br>  const myArrowFunction = () =&gt; {    <br>     console.log(arguments); <br>  }<br>  myArrowFunction(&#39;c&#39;, &#39;d&#39;);<br>}</pre><pre>myRegularFunction(&#39;a&#39;, &#39;b&#39;); // logs { 0: &#39;a&#39;, 1: &#39;b&#39; }</pre><p>The arrow function myArrowFunction() is invoked with the arguments &#39;c&#39;, &#39;d&#39;. Still, inside of its body, arguments object equals to the arguments of myRegularFunction() invocation: &#39;a&#39;, &#39;b&#39;.</p><p>If you’d like to access the direct arguments of the arrow function, then you can use the rest parameters feature:</p><pre>function myRegularFunction() {<br>  const myArrowFunction = (...args) =&gt; {    console.log(args);  }<br>  myArrowFunction(&#39;c&#39;, &#39;d&#39;);<br>}</pre><pre>myRegularFunction(&#39;a&#39;, &#39;b&#39;); // logs { 0: &#39;c&#39;, 1: &#39;d&#39; }</pre><p>...args rest parameter collects the execution arguments of the arrow function: { 0: &#39;c&#39;, 1: &#39;d&#39; }.</p><h3>4. Implicit return</h3><h4>4.1 Regular function</h4><p>Just use return expression statement to return a result from a function:</p><pre>function myFunction() {<br>  return 42;<br>}</pre><pre>myFunction(); // =&gt; 42</pre><p>If the return statement is missing, or there’s no expression after return statement, the regular function implicitly returns undefined:</p><pre>function myEmptyFunction() {<br>  42;<br>}</pre><pre>function myEmptyFunction2() {<br>  42;<br>  return;<br>}</pre><pre>myEmptyFunction();  // =&gt; undefined<br>myEmptyFunction2(); // =&gt; undefined</pre><h4>4.2 Arrow function</h4><p>You can return values from the arrow function the same way as from a regular function, but with one useful exception.</p><p>If the arrow function contains one expression, and you omit the function’s curly braces, then the expression is explicitly returned. These are the inline arrows function.</p><pre>const increment = (num) =&gt; num + 1;</pre><pre>increment(41); // =&gt; 42</pre><p>The increment() arrow consists of only one expression: num + 1. This expression is implicitly returned by the arrow function without the use of return keyword.</p><h3>5. Methods</h3><h4>5.1 Regular function</h4><p>The regular functions are the usual way to define methods on classes.</p><p>In the following class Hero, the method logName() is defined using a regular function:</p><pre>class Hero {<br>  constructor(heroName) {<br>    this.heroName = heroName;<br>  }</pre><pre>  logName() {    <br>     console.log(this.heroName);  <br>  }<br>}</pre><pre>const batman = new Hero(&#39;Batman&#39;);</pre><p>Usually, the regular functions as methods are the way to go.</p><p>Sometimes you’d need to supply the method as a callback, for example to setTimeout() or an event listener. In such cases, you might encounter difficulties to access this value.</p><p>For example, let’s use use logName() method as a callback to setTimeout():</p><pre>setTimeout(batman.logName, 1000);<br>// after 1 second logs &quot;undefined&quot;</pre><p>After 1 second, undefined is logged to console. setTimeout() performs a simple invocation of logName (where this is the global object). That’s when the method is separated from the object.</p><p>Let’s bind this value manually to the right context:</p><pre>setTimeout(batman.logName.bind(batman), 1000);<br>// after 1 second logs &quot;Batman&quot;</pre><p>batman.logName.bind(batman) binds this value to batman instance. Now you’re sure that the method doesn’t lose the context.</p><p>Binding this manually requires boilerplate code, especially if you have lots of methods. There’s a better way: the arrow functions as a class field.</p><h4>5.2 Arrow function</h4><p>Thanks to <a href="https://github.com/tc39/proposal-class-fields">Class fields proposal</a> you can use the arrow function as methods inside classes.</p><p>Now, in contrast with regular functions, the method defined using an arrow binds this lexically to the class instance.</p><p>Let’s use the arrow function as a field:</p><pre>class Hero {<br>  constructor(heroName) {<br>    this.heroName = heroName;<br>  }</pre><pre>  logName = () =&gt; {    console.log(this.heroName);  }}</pre><pre>const batman = new Hero(&#39;Batman&#39;);</pre><p>Now you can use batman.logName as a callback without any manual binding of this. The value of this inside logName() method is always the class instance:</p><pre>setTimeout(batman.logName, 1000);<br>// after 1 second logs &quot;Batman&quot;</pre><h3>6. Summary</h3><p>Understanding the differences between regular and arrow functions helps choose the right syntax for specific needs.</p><p>this value inside a regular function is dynamic and depends on the invocation. But this inside the arrow function is bound lexically and equals to this of the outer function.</p><p>arguments object inside the regular functions contains the list of arguments. The arrow function, on the opposite, doesn’t define arguments (but you can easily access the arrow function arguments using a rest parameter ...args).</p><p>If the arrow function has one expression, then the expression is returned implicitly, even without using the return keyword.</p><p>Last but not least, you can define methods using the arrow function syntax inside classes. Fat arrow methods bind this value to the class instance.</p><p>Anyhow the fat arrow method is invoked, this always equals to the class instance, which is useful when the methods are used as callbacks.</p><h4>JavaScript In Plain English</h4><p>Did you know that we have four publications and a YouTube channel? Find them all at <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> and <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>subscribe to Decoded, our YouTube channel</strong></a><strong>!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=401c4bf22ad3" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-differences-between-arrow-and-regular-functions-you-should-know-401c4bf22ad3">The Differences Between Arrow and Regular Functions You Should Know</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[5 Simple Tips to Write Better Arrow Functions]]></title>
            <link>https://javascript.plainenglish.io/5-simple-tips-to-write-better-arrow-functions-a55f40f63d58?source=rss-96bf7d1fdcfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/a55f40f63d58</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Fri, 15 May 2020 15:57:17 GMT</pubDate>
            <atom:updated>2020-06-30T12:34:53.534Z</atom:updated>
            <content:encoded><![CDATA[<h4>The arrow function is powerful but you should use it properly.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vf3fa6S1k6hO6KtB" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In ECMAScript2015, the arrow function was added. It is more concise than traditional functions, and binds this lexically.</p><p>The correct use of arrow functions can improve the quality of our code. However, many programmers have misunderstandings about the arrow function and can not play the role of the arrow function. Here are some of the lessons I learned before that I hope will help you.</p><h3>1. Add name for arrow function</h3><p>All traditional functions have their own names, except for arrow functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*U4BLuQu6bivl8KJrpBNEVg.png" /></figure><p>But the arrow function in JavaScript is anonymous: the name property of the function is an empty string &#39;&#39; default.</p><pre>( number =&gt; number * 2 ).name; // &quot;&quot;</pre><pre>( number =&gt; number - 1 ).name; // &quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*jjGDSrn4jWT37T6OwG3TRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*0XtUubejY4xprsLEXzpSHg.png" /></figure><p>And then you might ask: what does this name property do?</p><p>You may not need this property in your code, but it is very useful when we need to debug.</p><p>Assume we had this piece of code:</p><pre>let counter = 0;</pre><pre>setTimeout(() =&gt; {<br>  setInterval(() =&gt; {<br>    debugger;<br>    counter++;<br>  }, 1000)<br>}, 1000)</pre><p>Here’s a debug session of the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AolISR7d9nOGmK7c6Md0Xg.png" /><figcaption>From Chrome Debug Console</figcaption></figure><p>We can see that in Call Stack, array functions are marked as anonymous indeed. And we can’t get anything useful from such call stack information.</p><p>To facilitate debugging, it is necessary to add a name to the arrow function. Let’s see how to add a function name for arrow functions:</p><p>Here is an example:</p><pre>const increaseCounter = number =&gt; number++;</pre><pre>increaseCounter.name; // =&gt; &#39;increaseCounter&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJ5q0qQXw6W58ic4xBGHfA.png" /></figure><p>Because the variable increaseCounter holds the arrow function, JavaScript decides that &#39;increaseCounter&#39; could be a good name for that function. Thus the arrow function receives the name &#39;increaseNumber&#39;.</p><blockquote>A good practice is to add a function name inference to name the arrow functions.</blockquote><p>Now let’s check a debug session with code that uses name inference:</p><pre>let counter = 0;</pre><pre>const increaseCounter = () =&gt; {<br>  debugger;<br>  counter++;<br>}</pre><pre>const callback = () =&gt; {<br>  setInterval(increaseCounter, 1000)<br>}</pre><pre>setTimeout(callback, 1000)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I13UAncBU2DXx6yV9GXRnw.png" /></figure><p>Because the arrow functions have names, the call stack gives more information about the code being executed:</p><ul><li>callback is a function to call increaseCounter .</li><li>increaseCounter increases a counter variable.</li></ul><h3>2. Inline when possible</h3><p>An inline function is a function that has only one expression. I like about arrow functions the ability to compose short inline functions.</p><p>For example, instead of using the long form of an arrow function:</p><pre>const array = [1, 2, 3];</pre><pre>array.map((number) =&gt; { <br>  return number * 2;<br>});</pre><p>You could easily remove the curly braces { } and return statement when the arrow function has one expression:</p><pre>const array = [1, 2, 3];</pre><pre>array.map(number =&gt; number * 2);</pre><p>Here’s my advice:</p><blockquote>When the function has one expression, a good practice is to inline the arrow function.</blockquote><h3>3. Fat arrow and comparison operators</h3><p>The comparison operators &gt;, &lt;, &lt;= and &gt;= look similar to the fat arrow =&gt; (which defines the arrow function).</p><p>When these comparison operators are used in an inline arrow function, it creates some confusion.</p><p>Let’s define an arrow function that uses &lt;= operator:</p><pre>const negativeToZero = number =&gt; number &lt;= 0 ? 0 : number;</pre><p>The presence of both symbols =&gt; and &lt;= on the same line is misleading.</p><p>To distinguish clearly the fat arrow from the comparison operator, the first option is to wrap the expression into a pair of parentheses:</p><pre>const negativeToZero = number =&gt; (number &lt;= 0 ? 0 : number);</pre><p>The second option is to deliberately define the arrow function using a longer form:</p><pre>const negativeToZero = number =&gt; {<br>  return number &lt;= 0 ? 0 : number;<br>};</pre><p>These refactorings eliminate the confusion between fat arrow symbol and comparison operators.</p><blockquote>If the arrow function contains the operators &gt;, &lt;, &lt;= and &gt;=, a good practice is to wrap the expression into a pair of parentheses or deliberately use a longer arrow function form.</blockquote><h3>4. Constructing plain objects</h3><p>An object literal inside an inline arrow function triggers a syntax error:</p><pre>const array = [1, 2, 3];</pre><pre>// throws SyntaxError!<br>array.map(number =&gt; { &#39;number&#39;: number });</pre><p>JavaScript considers the curly braces a code block, rather than an object literal.</p><p>Wrapping the object literal into a pair of parentheses solves the problem:</p><pre>const array = [1, 2, 3];</pre><pre>// Works!<br>array.map(number =&gt; ({ &#39;number&#39;: number }));</pre><p>If the object literal has lots of properties, you can even use newlines, while still keeping the arrow function inline:</p><pre>const array = [1, 2, 3];</pre><pre>// Works!<br>array.map(number =&gt; ({<br>  &#39;number&#39;: number<br>  &#39;propA&#39;: &#39;value A&#39;,<br>  &#39;propB&#39;: &#39;value B&#39;<br>}));</pre><p>My recommendation:</p><blockquote>Wrap object literals into a pair of parentheses when used inside inline arrow functions.</blockquote><h3>5. Be aware of excessive nesting</h3><p>The arrow function syntax is short, which is good. But as a side effect, it could be cryptic when many arrow functions are nested.</p><p>Let’s consider the following scenario. When a button is clicked, a request to server starts. When the response is ready, the items are logged to console:</p><pre>myButton.addEventListener(&#39;click&#39;, () =&gt; {<br>  fetch(&#39;/items.json&#39;)<br>    .then(response =&gt; response.json())<br>    .then(json =&gt; {<br>      json.forEach(item =&gt; {<br>        console.log(item.name);<br>      });<br>    });<br>});</pre><p>The arrow functions are 3 levels nesting. It takes effort and time to understand what the code does.</p><p>To increase the readability of nested functions, the first approach is to introduce variables that each holds an arrow function. The variable should describe concisely what the function doe.</p><pre>const readItemsJson = json =&gt; {<br>  json.forEach(item =&gt; console.log(item.name));<br>};</pre><pre>const handleButtonClick = () =&gt; {<br>  fetch(&#39;/items.json&#39;)<br>    .then(response =&gt; response.json())<br>    .then(readItemsJson);<br>};</pre><pre>myButton.addEventListener(&#39;click&#39;, handleButtonClick);</pre><p>The refactoring extracts the arrow functions into variables readItemsJson and handleButtonClick. The level of nesting decreases from 3 to 2. Now, it’s easier to understand what the script does.</p><p>Even better you could refactor the entire function to use async/await syntax, which is a great way to solve the nesting of functions:</p><pre>const handleButtonClick = async () =&gt; {<br>  const response = await fetch(&#39;/items.json&#39;);<br>  const json = await response.json();<br>  json.forEach(item =&gt; console.log(item.name));<br>};</pre><pre>myButton.addEventListener(&#39;click&#39;, handleButtonClick);</pre><p>Resuming:</p><blockquote>A good practice is to avoid excessive nesting of arrow functions by extracting them into variables as separate functions or, if possible, embrace async/await syntax.</blockquote><h3>Conclusion</h3><p>The arrow functions in JavaScript are anonymous. To make debugging productive, a good practice is to use variables to hold the arrow functions. This allows JavaScript to infer the function names.</p><p>An inline arrow function is handy when the function body has one expression.</p><p>The operators &gt;, &lt;, &lt;= and &gt;= look similar to the fat arrow =&gt;. Care must be taken when these operators are used inside inline arrow functions.</p><p>The object literal syntax { prop: &#39;value&#39; } is similar to a code of block { }. So when the object literal is placed inside an inline arrow function, you need to wrap it into a pair of parentheses: () =&gt; ({ prop: &#39;value&#39; }).</p><p>Finally, the excessive nesting of functions obscures the code intent. A good approach to reduce the arrow functions nesting is to extract them into variables. Alternatively, try to use even better features like async/await syntax.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a55f40f63d58" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/5-simple-tips-to-write-better-arrow-functions-a55f40f63d58">5 Simple Tips to Write Better Arrow Functions</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[The Ultimate Guide to Array methods in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/everything-you-need-to-know-about-array-methods-in-javascript-97899e85163c?source=rss-96bf7d1fdcfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/97899e85163c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Sat, 09 May 2020 20:34:27 GMT</pubDate>
            <atom:updated>2020-05-09T20:35:00.317Z</atom:updated>
            <content:encoded><![CDATA[<h4>A code guide that you can add to your favorites</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qQnBK7E-wFMtb3Sg" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_source=medium&amp;utm_medium=referral">Paweł Czerwiński</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The array is one of the most important data structures in JavaScript. The number of operations you can perform on arrays (iteration, inserting items, removing items, etc) is big. The array object provides a decent number of useful methods like array.forEach(), array.map() and more.</p><p>Often I find myself overwhelmed by the number of possible operations on arrays and the corresponding implementations. You might be in the same situation too.</p><p>Therefore, I summarized relevant knowledge points, hoping that this can help me and you.</p><h4>Table of Contents</h4><ol><li>Iterate</li><li>Map</li><li>Reduce</li><li>Concat</li><li>Slice</li><li>Clone</li><li>Search</li><li>Query</li><li>Filter</li><li>Insert</li><li>Remove</li><li>Empty</li><li>Fill</li><li>Flatten</li><li>Sort</li></ol><h3>1: Iterate</h3><p>Looping through an array is probably the most operation we do with arrays. Do you know how many ways we can loop through arrays?</p><h4>1.1: for..of</h4><p>for(const item of items) cycle iterates over array items.</p><p>Let’s iterate over a list of colors:</p><pre>const colors = [&#39;blue&#39;, &#39;green&#39;, &#39;white&#39;];</pre><pre>for (const color of colors) {<br>  console.log(color);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3Cay_ivh3MXM_ivsCzTxQ.png" /></figure><p>On each iteration, the variable color is assigned with the iterated item.</p><p>Tips:</p><ul><li>You can stop iterating at any time using a break statement.</li></ul><h4>1.2: for cycle</h4><p>for(let i; i &lt; array.length; i++) cycle iterates over array items using an incrementing index variable.</p><p>for usually requires index variable that increments on each cycle:</p><pre>const colors = [&#39;blue&#39;, &#39;green&#39;, &#39;white&#39;];</pre><pre>for (let index = 0; index &lt; colors.length; index++) {<br>  const color = colors[index];<br>  console.log(color);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5N-Hb6oRHrlQY-KfpbTo7Q.png" /></figure><p>index variable increments from 0 until colors.length - 1. This variable is used to access the item by index: colors[index].</p><p>Tips:</p><ul><li>You can stop iterating at any time using a break statement.</li></ul><h4>1.3: array.forEach() method</h4><p>array.forEach(callback) method iterates over array items by invoking callback function on every array item.</p><p>On each iteration callback(item [, index [, array]]) is called with arguments: iterated item, index and the array itself.</p><p>Let’s iterate over colors array:</p><pre>const colors = [&#39;blue&#39;, &#39;green&#39;, &#39;white&#39;];</pre><pre>colors.forEach(function callback(value, index) {<br>  console.log(value, index);<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcV-SYNEUlAafVhoKKe0iA.png" /></figure><p>array.forEach(callback) invokes callback 3 times for every item in the array: &#39;blue&#39;, &#39;green&#39; and &#39;white&#39;.</p><p>Tips:</p><ul><li>You cannot break array.forEach() iterating.</li></ul><h3>2: Map</h3><h4>2.1: array.map() method</h4><p>array.map(callback) method creates to a new array by using callback invocation result on each array item.</p><p>On each iteration callback(item[, index[, array]]) is invoked with arguments: current item, index and the array itself. It should return the new item.</p><p>Let’s increment the numbers of an array:</p><pre>const numbers = [0, 2, 4];</pre><pre>const newNumbers = numbers.map(function increment(number) {<br>  return number + 1;<br>});</pre><pre>console.log(newNumbers);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLGFYR7dj-Vzv_p4qK_jdw.png" /></figure><p>numbers.map(increment) creates a new array from numbers by incrementing each array item.</p><p>Tips:</p><ul><li>array.map() creates a new mapped array, without mutating the original one.</li></ul><h4>2.2: Array.from() function</h4><p>Array.from(arrayLike[, callback]) method creates to a new array by using callback invocation result on each array item.</p><p>On each iteration callback(item[, index[, array]]) is invoked with arguments: current item, index and the array itself. It should return the new item.</p><p>Let’s increment the numbers of an array:</p><pre>const numbers = [0, 2, 4];</pre><pre>const newNumbers = Array.from(numbers,<br>  function increment(number) {<br>    return number + 1;<br>  }<br>);</pre><pre>console.log(newNumbers);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*VxQc6eQVjvDmMf-rYgnDEg.png" /></figure><p>Array.from(numbers, increment) creates a new array from numbers by incrementing each array item.</p><p>Tips:</p><ul><li>Array.from() creates a new mapped array, without mutating the original one</li><li>Array.from() fits better to map from an <a href="https://dmitripavlutin.com/javascript-array-from-applications/#2-transform-array-like-into-an-array">array-like object</a>.</li></ul><h3>3: Reduce</h3><h4>3.1: array.reduce() method</h4><p>array.reduce(callback[, initialValue]) reduces the array to a value by invoking callback function as a reducer.</p><p>On each iteration callback(accumulator, item[, index[, array]]) is invoked with arguments: accumulator, current item, index and the array itself. It should return the accumulator.</p><p>The classic example is summing an array of numbers:</p><pre>const numbers = [2, 0, 4];</pre><pre>function summarize(accumulator, number) {<br>  return accumulator + number;<br>}</pre><pre>const sum = numbers.reduce(summarize, 0);</pre><pre>console.log(sum);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5MirDcI578CCfRhAuKqbew.png" /></figure><p>At first step accumulator is initialized with 0. Then summarize function is invoked on each array item accumulating the sum of numbers.</p><p>Tips:</p><ul><li>The first array item becomes the initial value if you skip the initialValue argument.</li></ul><h3>4: Concat</h3><h4>4.1: array.concat() method</h4><p>array.concat(array1[, array2, ...]) concatenates to the original array one or more arrays.</p><p>Let’s concatenate 2 arrays of names:</p><pre>const heroes = [&#39;Batman&#39;, &#39;Robin&#39;];<br>const villains = [&#39;Joker&#39;, &#39;Bane&#39;];</pre><pre>const everyone = heroes.concat(villains);</pre><pre>console.log(everyone);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5niXKbEBbNPpLB7vxLbtIg.png" /></figure><p>heroes.concat(villains) creates a new array by concatenating heroes and villains arrays.</p><p>Tips:</p><ul><li>array.concat() creates a new array, without mutating the original one</li><li>array.concat(array1[, array2, ...]) accepts multiple arrays to concat.</li></ul><h4>4.2: Spread operator</h4><p>You can use the spread operator with an array literal to concatenate arrays: [...array1, ...array2].</p><p>Let’s concatenate 2 arrays of names:</p><pre>const heroes = [&#39;Batman&#39;, &#39;Catwoman&#39;];<br>const villains = [&#39;Joker&#39;, &#39;Bane&#39;];</pre><pre>const names = [...heroes, ...villains];</pre><pre>console.log(names);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJC0o3GrBrp-Q1uhqUTL0A.png" /></figure><p>[...heroes, ...villains] spreads heroes and villains items, then creates a new array containing all spread items.</p><ul><li>[...arr1, ...arr2, ...arrN]: you can concat as many arrays as you need using spread operator.</li></ul><h3>5: Slice</h3><h4>5.1: array.slice() method</h4><p>array.slice([fromIndex[, toIndex]]) returns a slice of the array starting fromIndex and ending toIndex (excluding toIndex itself). fromIndex optional argument defaults to 0, toIndex optional argument defaults to array.length.</p><p>Let’s get some array slices:</p><pre>const names = [&#39;Batman&#39;, &#39;Catwoman&#39;, &#39;Joker&#39;, &#39;Bane&#39;];</pre><pre>const heroes = names.slice(0, 2);<br>const villains = names.slice(2);</pre><pre>console.log(heroes);<br>console.log(villains);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlhBXFfr34sOpurSqTW3oA.png" /></figure><p>names.slice(0, 2) returns a slice of 2 items from names array.</p><p>names.slice(2) returns a slice of 2 items. The end argument defaults to names.length.</p><p>Tips:</p><ul><li>array.slice() creates a new array, without mutating the original one.</li></ul><h3>6: Clone</h3><h4>6.1: Spread operator</h4><p>An easy way to clone an array is to use the spread operator: const clone = [...array];</p><p>Let’s clone an array of colors:</p><pre>const colors = [&#39;white&#39;, &#39;black&#39;, &#39;gray&#39;];</pre><pre>const clone = [...colors];</pre><pre>console.log(clone); <br>console.log(colors === clone);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hoC3CqAn65In4f1c1BagRQ.png" /></figure><p>[...colors] creates a clone of colors array.</p><p>Tips:</p><ul><li>[...array] creates a shallow copy.</li></ul><h4>6.2: array.concat() method</h4><p>[].concat(array) is yet another approach on how to clone array.</p><pre>const colors = [&#39;white&#39;, &#39;black&#39;, &#39;gray&#39;];</pre><pre>const clone = [].concat(colors);</pre><pre>console.log(clone); <br>console.log(colors === clone);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5VYBuBJtlBNkRwSQJnSMQ.png" /></figure><p>[].concat(colors) creates a clone of colors array.</p><p>Tips:</p><ul><li>[].concat(array) creates a shallow copy.</li></ul><h4>6.3: array.slice() method</h4><p>array.slice() is another approach on how to clone array.</p><pre>const colors = [&#39;white&#39;, &#39;black&#39;, &#39;gray&#39;];</pre><pre>const clone = colors.slice();</pre><pre>console.log(clone); <br>console.log(colors === clone);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8at3lpQJmGq_K4VJ7W08w.png" /></figure><p>colors.slice() creates a clone of colors array.</p><p>Tips:</p><ul><li>colors.slice() creates a shallow copy.</li></ul><h3>7: Search</h3><h4>7.1: array.includes() method</h4><p>array.includes(itemToSearch[, fromIndex]) returns a boolean whether array contains itemToSearch. The optional argument fromIndex, defaulting to 0, indicates the index to start searching.</p><p>Let’s determine if 2 and 99 exist in an array of numbers:</p><pre>const numbers = [1, 2, 3, 4, 5];</pre><pre>numbers.includes(2);<br>numbers.includes(99);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*bgYM41-Kw_tajA3Dh1Y5hA.png" /></figure><p>numbers.includes(2) returns true because 2 exists in numbers array.</p><p>numbers.includes(99) is, however, false because numbers doesn’t contain 99.</p><h4>7.2: array.find() method</h4><p>array.find(predicate) method returns the first array item that satisfies the predicate function.</p><p>On each iteration predicate(item[, index[, array]]) function is invoked with the arguments: iterated item, index and the array itself.</p><p>For example, let’s find the first even number:</p><pre>const numbers = [1, 2, 3, 4, 5];</pre><pre>function isEven(number) {<br>  return number % 2 === 0;<br>}</pre><pre>const evenNumber = numbers.find(isEven);</pre><pre>console.log(evenNumber);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wEvurA5BV-D0N7xTGyrlkw.png" /></figure><p>numbers.find(isEven) returns the first even number inside numbers, which is 2.</p><p>Tips:</p><ul><li>array.find() returns undefined if no item has satisfied the predicate.</li></ul><h4>7.3: array.indexOf() method</h4><p>array.indexOf(itemToSearch[, fromIndex]) returns the index of the first appearance itemToSearch in array. The optional argument fromIndex, defaulting to 0, is the index to start searching.</p><p>Let’s find the index of &#39;Joker&#39;:</p><pre>const names = [&#39;Batman&#39;, &#39;Catwoman&#39;, &#39;Joker&#39;, &#39;Bane&#39;];</pre><pre>const index = names.indexOf(&#39;Joker&#39;);</pre><pre>console.log(index);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-NMWW8cU7g16PeNFX92_Vw.png" /></figure><p>The index of &#39;Joker&#39; inside names is 2.</p><p>Tips:</p><ul><li>array.indexOf(itemToSearch) returns -1 if the item hasn’t been found</li><li>array.findIndex(predicate) is an alternative to find the index using a predicate function.</li></ul><h3>8: Query</h3><h4>8.1: array.every() method</h4><p>array.every(predicate) method returns true if every item passes predicate check.</p><p>On each iteration predicate(item[, index[, array]]) predicate function is invoked with the arguments: iterated item, index and the array itself.</p><p>Let’s determine whether arrays evens and mix contain only even numbers:</p><pre>const evens = [0, 2, 4, 6];<br>const numbers = [0, 1, 4, 6];</pre><pre>function isEven(number) {<br>  return number % 2 === 0;<br>}</pre><pre>evens.every(isEven);<br>numbers.every(isEven);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*3gUFULn6xgh_P5NGub27KQ.png" /></figure><p>evens.every(isEven) is true because <em>all</em> numbers in evens are even.</p><p>However, numbers.every(isEven) evaluates to false because numbers contains an odd number 1.</p><h4>8.2: array.some() method</h4><p>array.some(predicate) method returns true if at least one item passes predicate check.<br>On each iteration predicate(item[, index[, array]]) function is invoked with the arguments: iterated item, index and the array itself.</p><p>Let’s determine whether the arrays contain at least one even number:</p><pre>const numbers = [1, 5, 7, 10];<br>const odds = [1, 3, 3, 3];</pre><pre>function isEven(number) {<br>  return number % 2 === 0;<br>}</pre><pre>numbers.some(isEven); // =&gt; true<br>odds.some(isEven);   // =&gt; false</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*qGvLYykajnuKFh43pC70Cw.png" /></figure><p>numbers.some(isEven) is true because at least one even number, 10, exists in numbers.</p><p>But odds.some(isEven) is false because odds contains only odd numbers.</p><h3>9: Filter</h3><h4>9.1: array.filter()</h4><p>array.filter(predicate) method returns a new array with items that have passed predicate check.</p><p>On each iteration predicate(item[, index[, array]]) function is invoked with the arguments: iterated item, index and the array itself.</p><p>Let’s filter an array to have only even numbers:</p><pre>const numbers = [1, 5, 7, 10];</pre><pre>function isEven(number) {<br>  return number % 2 === 0;<br>}</pre><pre>const evens = numbers.filter(isEven);</pre><pre>evens; // =&gt; [10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*LCEIgCgZPnfAzOANs-Ft1g.png" /></figure><p>numbers.filter(isEven) creates a new array evens by filtering numbers to contain only even numbers.</p><p>Tips:</p><ul><li>array.filter() creates a new array, without mutating the original one.</li></ul><h3>10: Insert</h3><h4>10.1: array.push() method</h4><p>array.push(item1[..., itemN]) method appends one or more items to the end of an array, returning the new length.</p><p>Let’s append &#39;Joker&#39; at the end of names array:</p><pre>const names = [&#39;Batman&#39;];</pre><pre>names.push(&#39;Joker&#39;);</pre><pre>names; // [&#39;Batman&#39;, &#39;Joker&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*zeIJTgmHH0R0ViyevcBDJg.png" /></figure><p>names.push(&#39;Joker&#39;) inserts a new item &#39;Joker&#39; at the end of the names array.</p><p>Tips:</p><ul><li>array.push() mutates the array in place</li><li>array.push(item1, item2, ..., itemN) can push multiple items.</li></ul><h4>10.2: array.unshift() method</h4><p>array.unshift(item1[..., itemN]) method appends one or more items to the beginning of an array, returning the new length of the array.</p><p>Let’s append &#39;Catwoman&#39; at the beginning of names array:</p><pre>const names = [&#39;Batman&#39;];</pre><pre>names.unshift(&#39;Catwoman&#39;);</pre><pre>names; // [&#39;Catwoman&#39;, &#39;Batman&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*5LXdVpyrz7weDp-UTF7ihQ.png" /></figure><p>names.unshift(&#39;Catwoman&#39;) inserts a new item &#39;Catwoman&#39; at the beginning of names array.</p><p>Tips:</p><ul><li>array.unshift() mutates the array in place.</li><li>array.unshift(item1, item2, ..., itemN) can insert multiple items.</li></ul><h4>10.3: Spread operator</h4><p>You can insert items in an array in an immutable manner by combining the spread operator with the array literal.</p><p>Appending an item at the <em>end of an array</em>:</p><pre>const names = [&#39;Joker&#39;, &#39;Bane&#39;];</pre><pre>const names2 = [<br>  ...names,<br>  &#39;Batman&#39;,<br>];</pre><pre>names2; // =&gt; [&#39;Joker&#39;, &#39;Bane&#39;, &#39;Batman&#39;];</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzEpw4JgyDg0ml8uvwQI2A.png" /></figure><p>Appending an item at the <em>beginning of an array</em>:</p><pre>const names = [&#39;Joker&#39;, &#39;Bane&#39;];</pre><pre>const names2 = [<br>  &#39;Batman&#39;,<br>  ...names<br>];</pre><pre>names2; // =&gt; [&#39;Batman&#39;, &#39;Joker&#39;, &#39;Bane&#39;];</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzEpw4JgyDg0ml8uvwQI2A.png" /></figure><p>Inserting an item <em>at any index</em>:</p><pre>const names = [&#39;Joker&#39;, &#39;Bane&#39;];<br>const indexToInsert = 1;</pre><pre>const names2 = [<br>  ...names.slice(0, indexToInsert),<br>  &#39;Batman&#39;,<br>  ...names.slice(indexToInsert)<br>];</pre><pre>names2; // =&gt; [&#39;Joker&#39;, &#39;Batman&#39;, &#39;Bane&#39;];</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*nop86N6o5pLwRQqU2X0L-w.png" /></figure><h3>11: Remove</h3><h4>11.1: array.pop() method</h4><p>array.pop() method removes the last item from an array, then returns that item.</p><p>For example, let’s remove the last element of colors array:</p><pre>const colors = [&#39;blue&#39;, &#39;green&#39;, &#39;black&#39;];</pre><pre>const lastColor = colors.pop();</pre><pre>console.log(lastColor);<br>console.log(colors);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWfgorn1_sFM7DJSsEq6-A.png" /></figure><p>colors.pop() removes the last element of colors and returns it.</p><p>Tips:</p><ul><li>array.pop() mutates the array in place.</li></ul><h4>11.2: array.shift() method</h4><p>array.shift() method removes the first item from an array, then returns that item.</p><p>For example, let’s remove the first element of colors array:</p><pre>const colors = [&#39;blue&#39;, &#39;green&#39;, &#39;black&#39;];</pre><pre>const firstColor = colors.shift();</pre><pre>console.log(firstColor);<br>console.log(colors);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lk5sJBqrK_Zm_LRsN1tT0w.png" /></figure><p>colors.shift() removes the first element &#39;blue&#39; of colors and returns it.</p><p>Tips:</p><ul><li>array.shift() mutates the array in place</li><li>array.shift() has O(n) complexity.</li></ul><h4>11.3: array.splice() method</h4><p>array.splice(fromIndex[, removeCount[, item1[, item2[, ...]]]]) removes items from an array and inserts new items instead.</p><p>For example, let’s remove 2 items from index 1:</p><pre>const names = [&#39;Batman&#39;, &#39;Catwoman&#39;, &#39;Joker&#39;, &#39;Bane&#39;];</pre><pre>names.splice(1, 2);</pre><pre>names; // =&gt; [&#39;Batman&#39;, &#39;Bane&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ysm63DQD43ChE-SR_RV1uQ.png" /></figure><p>names.splice(1, 2) removes the elements &#39;Catwoman&#39; and &#39;Joker&#39;.</p><p>names.splice() can insert new items instead of removed ones. Let’s replace 2 items from index 1, and insert a new item &#39;Alfred&#39; instead:</p><pre>const names = [&#39;Batman&#39;, &#39;Catwoman&#39;, &#39;Joker&#39;, &#39;Bane&#39;];</pre><pre>names.splice(1, 2, &#39;Alfred&#39;);</pre><pre>names; // =&gt; [&#39;Batman&#39;, &#39;Alfred&#39; ,&#39;Bane&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTcO7LRSSrU7GJQmtwi3Kg.png" /></figure><p>Tips:</p><ul><li>array.splice() mutates the array in place.</li></ul><h4>11.4: Spread operator</h4><p>You can remove items from an array in an immutable manner by combining the spread operator with the array literal.</p><p>Let’s remove a few items:</p><pre>const names = [&#39;Batman&#39;, &#39;Catwoman&#39;, &#39;Joker&#39;, &#39;Bane&#39;];<br>const fromIndex = 1;<br>const removeCount = 2;</pre><pre>const newNames = [<br>  ...names.slice(0, fromIndex),<br>  ...names.slice(fromIndex + removeCount)<br>];</pre><pre>newNames; // =&gt; [&#39;Batman&#39;, &#39;Bane&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OwBKjnwFdwd5-OfcMIRHg.png" /></figure><p>newNames contains the items of names, but without 2 that were removed.</p><h3>12: Empty</h3><h4>12.1: array.length property</h4><p>array.length is a property that holds the array length. More than that, array.length is writable.</p><p>If you write a smaller than current length array.length = newLength, the extra elements are removed from the array.</p><p>Let’s use array.length = 0 to remove all the items of an array:</p><pre>const colors = [&#39;blue&#39;, &#39;green&#39;, &#39;black&#39;];</pre><pre>colors.length = 0;</pre><pre>colors; // []</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*czRUtatwgccJG9eO8E7PBA.png" /></figure><p>colors.length = 0 removes all items from colors array.</p><h4>12.2: array.splice() method</h4><p>array.splice(fromIndex[, removeCount[, item1[, item2[, ...]]]]) removes items from an array and inserts new items instead.</p><p>If removeCount argument is omitted, then array.splice() removes all elements of the array starting fromIndex.</p><p>Let’s use this to remove all elements of an array:</p><pre>const colors = [&#39;blue&#39;, &#39;green&#39;, &#39;black&#39;];</pre><pre>colors.splice(0);</pre><pre>colors; // []</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*ERoUDDz2SgK9y86XHYPZag.png" /></figure><p>colors.splice(0) removes all elements of colors array.</p><h3>13: Fill</h3><h4>13.1: array.fill() method</h4><p>array.fill(value[, fromIndex[, toIndex]]) fills the array with value starting fromIndex until toIndex (excluding toIndex itself). fromIndex optional argument defaults to 0, toIndex optional argument defaults to array.length.</p><p>For example, let’s fill an array with zero values:</p><pre>const numbers = [1, 2, 3, 4];</pre><pre>numbers.fill(0);</pre><pre>numbers; // =&gt; [0, 0, 0, 0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*k822kbiRP7xFsyZ_tqz80A.png" /></figure><p>numbers.fill(0) fills the array with zeros.</p><p>More than that, you can initialize arrays of specific length and initial value using Array(length).fill(initial):</p><pre>const length = 3;<br>const zeros = Array(length).fill(0);</pre><pre>zeros; // [0, 0, 0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*hysgP6bKDngGLjPYfXlx1g.png" /></figure><p>Array(length).fill(0) creates an array of 3 zeros.</p><p>Tips:</p><ul><li>array.fill() mutates the array in place.</li></ul><h4>13.2: Array.from() function</h4><p>Array.from() can be useful to initialize an array of a certain length with objects:</p><pre>const length = 4;<br>const emptyObjects = Array.from(Array(length), function() {<br>  return {};<br>});</pre><pre>emptyObjects; // [{}, {}, {}, {}]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1OV6mrdAg84auT00Xo7jOQ.png" /></figure><p>emptyObjects is an array initialized with different instances of empty objects.</p><h3>14: Flatten</h3><h4>14.1: array.flat() method</h4><p>array.flat([depth]) creates a new array by recursively flatting the items that are arrays, until certain depth. depth optional argument defaults to 1.</p><p>Let’s flatten an array of arrays:</p><pre>const arrays = [0, [1, 3, 5], [2, 4, 6]];</pre><pre>const flatArray = arrays.flat();</pre><pre>flatArray; // [0, 1, 3, 5, 2, 4, 6]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*mrofW2gcuFhBRVjQ5di8hQ.png" /></figure><p>arrays contains a mix of numbers and arrays of numbers. arrays.flat() flats the array so that it contains only numbers.</p><p>Tips:</p><ul><li>array.flat() creates a new array, without mutating the original one.</li></ul><h3>15: Sort</h3><h4>15.1: array.sort() method</h4><p>array.sort([compare]) method sorts the items of the array. When the compare function is omitted, the method converts the items to strings, then orders them ascending by UTF-16 code units values.</p><p>The optional argument compare(item1, item2) is a callback that customizes the order of items. If compare(item1, item2) returns:</p><ul><li>-1 then item1 will follow by item2 in the sorted array</li><li>1 then item2 will follow by item1 in the sorted array</li><li>0 then the position of items doesn’t change</li></ul><p>Let’s sort an array of letters:</p><pre>const letters = [&#39;B&#39;, &#39;C&#39;, &#39;A&#39;];</pre><pre>letters.sort();</pre><pre>letters; // =&gt; [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*G1BFRFFf5jDUdlNul1bIeA.png" /></figure><p>letters.sort() sorts the letters in ascending order.</p><p>Let’s use the compare function and make even numbers followed by odd ones:</p><pre>const numbers = [4, 3, 1, 2];</pre><pre>function compare(n1, n2) {<br>  if (n1 % 2 === 0 &amp;&amp; n2 % 2 !== 0) {<br>    return -1;<br>  }<br>  if (n1 % 2 !== 0 &amp;&amp; n2 % 2 === 0) {<br>    return -1;<br>  }<br>  return 0;<br>}</pre><pre>numbers.sort(compare);</pre><pre>numbers;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*504NEXbTaPBbQlXED7cnZg.png" /></figure><p>numbers.sort(compare) uses the custom compare function that orders even numbers first.</p><p>Tips:</p><ul><li>array.sort() mutates the array in place.</li></ul><h4><strong>A note from the Plain English team</strong></h4><p>Did you know that we have four publications? Show some love by giving them a follow: <a href="https://medium.com/javascript-in-plain-english"><strong>JavaScript in Plain English</strong></a>, <a href="https://medium.com/ai-in-plain-english"><strong>AI in Plain English</strong></a>, <a href="https://medium.com/ux-in-plain-english"><strong>UX in Plain English</strong></a>, <a href="https://medium.com/python-in-plain-english"><strong>Python in Plain English</strong></a><strong> </strong>— thank you and keep learning!</p><p>Also, we’re always interested in helping to promote good content. If you have an article that you would like to submit to any of our publications, send an email to <a href="/service/mailto:submissions@plainenglish.io"><strong>submissions@plainenglish.io</strong></a><strong> </strong>with your Medium username and what you are interested in writing about and we will get back to you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97899e85163c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/everything-you-need-to-know-about-array-methods-in-javascript-97899e85163c">The Ultimate Guide to Array methods in JavaScript</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[JavaScript Interview Question: How to Implement a Promise?]]></title>
            <link>https://javascript.plainenglish.io/javascript-interview-question-how-to-implement-a-promise-1a2ac69b9a0d?source=rss-96bf7d1fdcfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a2ac69b9a0d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Tue, 05 May 2020 06:56:49 GMT</pubDate>
            <atom:updated>2020-05-05T06:56:49.724Z</atom:updated>
            <content:encoded><![CDATA[<h4>Write a Promise function step by step.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*itr4Ob8DbH3Ih5qa" /><figcaption>Photo by <a href="https://unsplash.com/@mmayyer?utm_source=medium&amp;utm_medium=referral">marcos mayer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Promise is a core feature of JavaScript from ES2015. A promise is an object that may produce a single value some time in the future: either a resolved value or a reason that it’s not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled(resolved), rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.</p><p>Our Promise function should adhere to the Promise A+ specification, and if you are not familiar with it, please read this specification first.</p><p><a href="https://promisesaplus.com/">Promises/A+</a></p><p>Next, let’s write a Promise function together.</p><h3>Executor</h3><p>We know that when you create a Promise instance, we need to pass in an executor function. The executor function should take two function arguments: the resolve function and the reject function. When the resolve function is invoked, the promise instance becomes resolved. If the executor function performs an exception, the reject function should be called, and the state of the Promise instance will be rejected.</p><p>Now, let’s write a MyPromise function that basically meets these requirements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8da17885caf856ab4150474b2d6f0175/href">https://medium.com/media/8da17885caf856ab4150474b2d6f0175/href</a></iframe><p>Attention, for better understanding, I use ES6’s class syntax. This is actually the syntax sugar for the constructor function.</p><p>All right, now let’s simply test the function we just wrote.</p><pre>let p1 = new MyPromise((resolve, reject) =&gt; {<br>    resolve(1);<br>})</pre><pre>let p2 = new MyPromise((resolve, reject) =&gt; {<br>    reject(2);<br>})</pre><pre>console.log(p1);<br>console.log(p2);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0ejzjpNzlGdENvnHeNdfA.png" /></figure><p>Ok, now we’ve written the MyPromise function and can correctly change the state through the resolve and reject functions.</p><h3>Then</h3><p>Next, let’s write the .then method for the MyPromise. The then method should have two function arguments, the first will be executed after the Promise succeeds and the second will be executed after the Promise fails.</p><p>At the same time, the .then method supports chain calls, which return an promise instance after each execution.</p><pre>new Promise((resolve, reject) =&gt; {<br>  resolve(1)<br>}).then(null, error =&gt; {<br>  console.log(error)<br>}).then(value =&gt; {<br>  console.log(1)<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*INU_H94FGYb7QAem6f_Kvw.png" /></figure><p>Now let’s refine the previous code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad5e1a8a9d94a5353bc6be3501bf18a9/href">https://medium.com/media/ad5e1a8a9d94a5353bc6be3501bf18a9/href</a></iframe><h3>catch</h3><p>The .catch method is used to catch exceptions. It is the same as the second callback function for the .then method.</p><p>So, we can just write it this way:</p><pre>catch(rejectFn) {<br>    return this.then(null, rejectFn)<br>}</pre><h3>resolve and reject</h3><p>We know thePromise.resolve(…) method is to return an instance of a Promise with a resolved state and thePromise.reject(…) method is to return an instance of a Promise with a rejected state. These two methods are very easy to implement:</p><pre>static resolve(result) {<br>    return new MyPromise(resolve =&gt; {<br>        resolve(result)<br>    })<br>}</pre><pre>static reject(reason) {<br>    return new MyPromise((_, reject) =&gt; {<br>        reject(reason);<br>    })<br>}</pre><h3>finally</h3><p>The finally() method returns a Promise. When the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with.</p><p>This is code snippet:</p><pre>finally(finallyFn) {<br>    let P = this.constructor;<br>    return this.then(<br>        value =&gt; P.resolve(finallyFn()).then(() =&gt; value),<br>        reason =&gt; P.reject(finallyFn()).then(() =&gt; reason)<br>    )<br>}</pre><p>This is full code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dcde43bb29ffa0b1298600337ace247/href">https://medium.com/media/9dcde43bb29ffa0b1298600337ace247/href</a></iframe><h3>all</h3><p>The Promise.all() method returns a single Promise that fulfills when all of the promises passed as an iterable have been fulfilled or when the iterable contains no promises or when the iterable contains promises that have been fulfilled and non-promises that have been returned. It rejects with the reason of the first promise that rejects, or with the error caught by the first argument if that argument has caught an error inside it using try/catch/throw blocks.</p><pre>// Receive array parameter<br>static all(promiseList) {<br>    // Returns a new instance<br>    return new MyPromise((resolve, reject) =&gt; {<br>        let index = 0,     <br>            results = []; <br>        <br>        for(let i = 0; i &lt; promiseList.length; i++) {<br>            let item = promiseList[i];<br>            <br>            if(!(item instanceof MyPromise)) return;<br>            <br>            item.then(result =&gt; {<br>                index++;<br>                results[i] = result;<br>                if(index === promiseList.length) {<br>                    resolve(results);<br>                }<br>            }).catch(reason =&gt; {<br>                reject(reason);<br>            })<br>        }<br>    })<br>}</pre><h4><strong>A note from JavaScript In Plain English</strong></h4><p>We have launched three new publications! Show some love for our new publications by following them: <a href="https://medium.com/ai-in-plain-english"><strong>AI in Plain English</strong></a>, <a href="https://medium.com/ux-in-plain-english"><strong>UX in Plain English</strong></a>, <a href="https://medium.com/python-in-plain-english"><strong>Python in Plain English</strong></a><strong> </strong>— thank you and keep learning!</p><p>We are also always interested in helping to promote quality content. If you have an article that you would like to submit to any of our publications, send us an email at <a href="/service/mailto:submissions@plainenglish.io"><strong>submissions@plainenglish.io</strong></a><strong> </strong>with your Medium username and we will get you added as a writer. Also let us know which publication/s you want to be added to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a2ac69b9a0d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/javascript-interview-question-how-to-implement-a-promise-1a2ac69b9a0d">JavaScript Interview Question: How to Implement a Promise?</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[Can you implement an async-await function with just 20 lines of code?]]></title>
            <link>https://javascript.plainenglish.io/can-you-implement-an-async-await-function-with-just-20-lines-of-code-1f5b187c6a4f?source=rss-96bf7d1fdcfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f5b187c6a4f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Mon, 04 May 2020 09:00:46 GMT</pubDate>
            <atom:updated>2020-05-04T09:00:46.610Z</atom:updated>
            <content:encoded><![CDATA[<h4>One thing that will make you stand out in an interview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vihKFiaE2zuuWuJJ" /><figcaption>Photo by <a href="https://unsplash.com/@moritz_photography?utm_source=medium&amp;utm_medium=referral">Moritz Kindler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If the interviewer asked you to write an async function by hand, would you be able to complete the task?</p><p>The async function is the syntax sugar of the generator function. In this article, I will first examine how the async keyword and the generator function work together to manage asynchronous programming. Then I’ll work with you to implement a simple async function using the generator function.</p><p>First, let’s look at a function that uses the async/await keyword.</p><pre>const getData = () =&gt; new Promise(resolve =&gt; setTimeout(() =&gt; resolve(&quot;data&quot;), 1000))</pre><pre>async function test() {<br>  const data = await getData()<br>  console.log(&#39;data: &#39;, data);<br>  const data2 = await getData()<br>  console.log(&#39;data2: &#39;, data2);<br>  return &#39;success&#39;<br>}</pre><pre>// The function will print `data` after 1 second, then `data2` after another second and then &#39;success&#39;<br>test().then(res =&gt; console.log(res))</pre><p>If we want to express the example above using the generator function, how should we write the code?</p><p>We can write it like this:</p><pre>const getData = () =&gt; new Promise(resolve =&gt; setTimeout(() =&gt; resolve(&quot;data&quot;), 1000))</pre><pre>function* testG() {<br>  // await is translated as yield<br>  const data = yield getData()<br>  console.log(&#39;data: &#39;, data);<br>  const data2 = yield getData()<br>  console.log(&#39;data2: &#39;, data2);<br>  return &#39;success&#39;<br>}</pre><p>As we know, the generator function does not execute automatically. Each time its next method is called, the program stops at the next yield.</p><p>With this feature, we can write an automatically executed function and have the generator function fully implement the async function.</p><pre>function asyncToGenerator(fn){<br>  // ...<br>}<br>  <br>var test = asyncToGenerator(<br>    function* testG() {<br>      // await is translated as yield<br>      const data = yield getData()<br>      console.log(&#39;data: &#39;, data);<br>      const data2 = yield getData()<br>      console.log(&#39;data2: &#39;, data2);<br>      return &#39;success&#39;<br>    }<br>)</pre><pre>test().then(res =&gt; console.log(res))</pre><p>Well, we haven’t written the asyncToGenerator function yet, but the overall idea is set. AsyncToGenerator should accept a generator function and return a promise object. The key here is that the function uses yield to partition asynchronous processes, so how should this be automated?</p><p>Before writing this function, we simulated manually calling the generator function and then walked through the process step by step, which helped us think better later.</p><pre>function* testG() {<br>  const data = yield getData()<br>  console.log(&#39;data: &#39;, data);<br>  const data2 = yield getData()<br>  console.log(&#39;data2: &#39;, data2);<br>  return &#39;success&#39;<br>}</pre><p>We first call testG to generate an iterator:</p><pre>// An iterator is returned<br>var gen = testG()</pre><p>Then execute next for the first time:</p><pre>// After the first call `next`, the program stays at the first yield<br>// The return promise object contains the data needed for `data`<br>var dataPromise = gen.next()</pre><p>A promise is returned, which is the promise returned by the first execution of getData().</p><pre>const data = yield getData()</pre><p>But note: this code is cut into left and right parts, and the first call to next is really just a stop at yield getData(), where the value of the data is not determined.</p><p>So when is the value of data determined? On the next call to next, the parameters passed in are accepted as values before the last yield.</p><p>That is, when we call gen.next(‘a value to data’) again, the value of the data will be determined as ‘a value to data’.</p><pre>gen.next(&#39;a value to data&#39;)</pre><pre>// This is when the data is assigned<br>const data = yield getData()</pre><pre>console.log(&#39;data: &#39;, data);</pre><pre>// Then go to next yield<br>const data2 = yield getData()</pre><p>This is a difficult point for the generator function to understand, but we have to learn it in order to achieve our goal.</p><p>With this feature, we can control the process of yield and then implement the asynchronous function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e307c0d1b552417a8c01b83927276ee6/href">https://medium.com/media/e307c0d1b552417a8c01b83927276ee6/href</a></iframe><p>Such a function call, which looks like a callback hell, lets async/await be implemented via the generator function.</p><p>This is our final code in 22 lines:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f4ebe9fb9c16a9311875bb073de94d2/href">https://medium.com/media/8f4ebe9fb9c16a9311875bb073de94d2/href</a></iframe><p>Then let’s analyze this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c0fe6808cc2bf33d1016c4ce7edbfd4/href">https://medium.com/media/9c0fe6808cc2bf33d1016c4ce7edbfd4/href</a></iframe><p>`</p><h4><strong>A note from JavaScript In Plain English</strong></h4><p>We have launched three new publications! Show some love for our new publications by following them: <a href="https://medium.com/ai-in-plain-english"><strong>AI in Plain English</strong></a>, <a href="https://medium.com/ux-in-plain-english"><strong>UX in Plain English</strong></a>, <a href="https://medium.com/python-in-plain-english"><strong>Python in Plain English</strong></a><strong> </strong>— thank you and keep learning!</p><p>We are also always interested in helping to promote quality content. If you have an article that you would like to submit to any of our publications, send us an email at <a href="/service/mailto:submissions@plainenglish.io"><strong>submissions@plainenglish.io</strong></a><strong> </strong>with your Medium username and we will get you added as a writer. Also let us know which publication/s you want to be added to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f5b187c6a4f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/can-you-implement-an-async-await-function-with-just-20-lines-of-code-1f5b187c6a4f">Can you implement an async-await function with just 20 lines of code?</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[Everything you need to know about Destructuring in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/everything-you-need-to-know-about-destructuring-in-javascript-5e9fde6e86ff?source=rss-96bf7d1fdcfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e9fde6e86ff</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Mon, 04 May 2020 08:02:15 GMT</pubDate>
            <atom:updated>2020-05-04T08:02:15.258Z</atom:updated>
            <content:encoded><![CDATA[<h4>Make your code more readable</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9QCHgXpo16_xwEqx" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The destructuring assignment is a cool feature that came along with ES6. Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from objects and arrays and assign them to variables.</p><h3>Object Destructuring</h3><p>First, let’s see why there is a need for object destructuring.</p><p>Say we want to extract data from an object and assign them to new variables. Prior to ES6, how would this be done?</p><pre>var person = {name: &quot;Tom&quot;, country: &quot;Canada&quot;, age: 35};</pre><pre>var name = person.name;<br>var country = person.country;<br>var age = person.age;</pre><pre>console.log(name);<br>console.log(country);<br>console.log(age);</pre><p>See how tedious it is to extract all the data. We have to repeatedly do the same thing. ES6 destructuring really saves the day. Let’s jump right into it.</p><h4>Basic Object Destructuring</h4><p>Let’s repeat the above example with ES6. Instead of assigning values one by one, we can use the object on the left to extract the data:</p><pre>var person = {name: &quot;Tom&quot;, country: &quot;Canada&quot;, age: 35};</pre><pre>var {name, country, age} = person;</pre><pre>console.log(name);<br>console.log(country);<br>console.log(age);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPKAJ5Kw3Y_CW7X21R22IQ.png" /></figure><p>You’ll get the same results. It is also valid to assign variables to an object that haven’t been declared:</p><pre>var {name, country, age} = {name: &quot;Tom&quot;, country: &quot;Canada&quot;, age: 35};</pre><pre>console.log(name);<br>console.log(country);<br>console.log(age);</pre><h4>Variables declared before being assigned</h4><p>Variables in objects can be declared before being assigned with destructuring. Let’s try that:</p><pre>var person = {name: &quot;Tom&quot;, country: &quot;Canada&quot;, age: 35};</pre><pre>var name, country, age;</pre><pre>{name, country, age} = person;</pre><pre>console.log(name);<br>console.log(country);<br>console.log(age);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knqNCkS76oFq8XxwDUw6TQ.png" /></figure><p>Wait, what just happened?! Oh, we forgot to add () before the curly brackets.</p><p>The ( ) around the assignment, the statement is required syntax when using the object literal destructuring assignment without a declaration. This is because the {} on the left-hand side is considered a block and not an object literal. So here&#39;s how to do this the right way:</p><pre>var person = {name: &quot;Tom&quot;, country: &quot;Canada&quot;, age: 35};</pre><pre>var name, country, age;</pre><pre>({name, country, age} = person);</pre><pre>console.log(name);<br>console.log(country);<br>console.log(age);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1nSrzr6LGd--Wo6gZtDuw.png" /></figure><p>It is also important to note that when using this syntax, the () should be preceded by a semicolon. Otherwise, it might be used to execute a function from the previous line.</p><p>Note that the variables in the object on the left-hand side should have the same name as a property key in the object person. If the names are different, we&#39;ll get undefined:</p><pre>var person = {name: &quot;Tom&quot;, country: &quot;Canada&quot;, age: 35};<br>var name, country, age;<br>({name, Country, Age} = person);</pre><pre>console.log(name);<br>console.log(country);<br>console.log(age);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzSOMyVRgXrO1IUYMBKyyg.png" /></figure><p>But if we want to use a new variable name, well, we can.</p><h4>Using a new Variable Name</h4><p>If we want to assign values of an object to a new variable instead of using the name of the property, we can do this:</p><pre>var person = {name: &quot;Tom&quot;, country: &quot;Canada&quot;, age: 35};</pre><pre>var {name, country: Country, age: Age} = person;</pre><pre>console.log(name);<br>console.log(Country);<br>console.log(Age);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjL4JD0k1ucpwejejchdsQ.png" /></figure><p>So the values extracted are passed to the new variables foo and bar.</p><h4>Using Default Values</h4><p>Default values can also be used in object destructuring, just in case a variable is undefined in an object it wants to extract data from:</p><pre>var person = {name: &quot;Tom&quot;, country: &quot;Canada&quot;, age: 35};</pre><pre>var {name, sex = &quot;male&quot;} = person;</pre><pre>console.log(name);<br>console.log(sex);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnWep8OSGgq54YzXkXQpeQ.png" /></figure><p>So if the value is not undefined, the variable stores the value extracted from the object as in the case of name. Otherwise, it used the default value as it did for sex.</p><h4>Computed Property Name</h4><p>A computed property name is another object literal feature that also works for destructuring. You can specify the name of a property via an expression if you put it in square brackets:</p><pre>var foo = &quot;name&quot;;</pre><pre>var {[foo]: bar} = {name: &quot;Tom&quot;, country: &quot;Canada&quot;, age: 35};</pre><pre>console.log(bar);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPDY86xBG4h15Qx4411CoA.png" /></figure><h4>Nesting in Object Destructuring</h4><p>Objects can also be nested when destructuring:</p><pre>let person = {<br>    name: &quot;Sarah&quot;,<br>    place: {<br>        country: &quot;Nigeria&quot;, <br>        city: &quot;Lagos&quot; }, <br>    friends : [&quot;Annie&quot;, &quot;Becky&quot;]<br>};</pre><pre>let {name:foo,<br>     place: {<br>         country : bar,<br>         city : x}<br>    } = person;</pre><pre>console.log(foo);//&quot;Sarah&quot;<br>console.log(bar);//&quot;Nigeria&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*3PIImHgzyAoHTHEW7CL26A.png" /></figure><h3>Array Destructuring</h3><p>If we want to extract data from arrays, it’s quite simple using the destructuring assignment.</p><pre>var human= [&quot;Tom&quot;, 35, &quot;Canada&quot;];</pre><pre>var [name, age, country] = human;</pre><pre>console.log(name);<br>console.log(age);<br>console.log(country);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5EaGJEF6UiKN6sF3Q1gFyg.png" /></figure><p>We can also do this with the same result.</p><pre>var [name, age, country] = [&quot;Tom&quot;, 35, &quot;Canada&quot;];</pre><pre>console.log(name);<br>console.log(age);<br>console.log(country);</pre><h4>Declaring Variables before Assignment</h4><p>Variables can be declared before being assigned like this:</p><pre>var name, age, country;<br>[name, age, country] = [&quot;Tom&quot;, 35, &quot;Canada&quot;];</pre><pre>console.log(name);<br>console.log(age);<br>console.log(country);</pre><p>Notice that the variables are set from left to right. So the first variable gets the first item in the array, the second variable gets the second variable in the array, and so on.</p><h4>Skipping Items in an Array</h4><p>What if we want to get the first and last item on our array instead of the first and second item, and we want to assign only two variables? This can also be done. Look at the example below:</p><pre>var name, age, country;<br>[name, , country] = [&quot;Tom&quot;, 35, &quot;Canada&quot;];</pre><pre>console.log(name);<br>console.log(country);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTeNtbuRJCaJpF-lMTzFiA.png" /></figure><p>The comma separator is used to skip values in an array.</p><h4>Assigning the rest of an array</h4><p>What if we want to assign some of the array to variables and the rest of the items in an array to a particular variable? In that case, we would do this:</p><pre>var [name, ...info] = [&quot;Tom&quot;, 35, &quot;Canada&quot;];</pre><pre>console.log(name);<br>console.log(info);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0qxya5kK9kwQDP2uRbvaAg.png" /></figure><p>Using this pattern, you can unpack and assign the remaining part of an array to a variable.</p><h4>Using Default Values</h4><p>Default values can be assigned to the variables just in case the value extracted from the array is undefined:</p><pre>var [name, age = 18, country = &quot;US&quot;] = [&quot;Tom&quot;];</pre><pre>console.log(name);<br>console.log(age);<br>console.log(country);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-f6qMTDvvncSI05uywdMVg.png" /></figure><p>So age falls back to 18 because it is not defined in the array.</p><h4>Swapping Values using the Destructuring Assignment</h4><p>One more thing. We can use the destructuring assignment to swap the values of variables:</p><pre>var a = 1;<br>var b = 0;</pre><pre>[a,b] = [b,a];</pre><pre>console.log(a); // 0<br>console.log(b); // 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*Pkznzcc9FnclXnOlEX_F6A.png" /></figure><h4><strong>A note from JavaScript In Plain English</strong></h4><p>We have launched three new publications! Show some love for our new publications by following them: <a href="https://medium.com/ai-in-plain-english"><strong>AI in Plain English</strong></a>, <a href="https://medium.com/ux-in-plain-english"><strong>UX in Plain English</strong></a>, <a href="https://medium.com/python-in-plain-english"><strong>Python in Plain English</strong></a><strong> </strong>— thank you and keep learning!</p><p>We are also always interested in helping to promote quality content. If you have an article that you would like to submit to any of our publications, send us an email at <a href="/service/mailto:submissions@plainenglish.io"><strong>submissions@plainenglish.io</strong></a><strong> </strong>with your Medium username and we will get you added as a writer. Also let us know which publication/s you want to be added to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e9fde6e86ff" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/everything-you-need-to-know-about-destructuring-in-javascript-5e9fde6e86ff">Everything you need to know about Destructuring in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>