<?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 Jihad Al Khurfan on Medium]]></title>
        <description><![CDATA[Stories by Jihad Al Khurfan on Medium]]></description>
        <link>https://medium.com/@jalkhurfan?source=rss-6f040e113bce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qKBh5z58AA6pyXR8kIU5CQ.png</url>
            <title>Stories by Jihad Al Khurfan on Medium</title>
            <link>https://medium.com/@jalkhurfan?source=rss-6f040e113bce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:07:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jalkhurfan/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[Leveling Up Your JavaScript (Part 1) — ES6 Edition]]></title>
            <link>https://medium.com/geekculture/leveling-up-your-javascript-part-1-es6-edition-13447e30980?source=rss-6f040e113bce------2</link>
            <guid isPermaLink="false">https://medium.com/p/13447e30980</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[advanced]]></category>
            <dc:creator><![CDATA[Jihad Al Khurfan]]></dc:creator>
            <pubDate>Sun, 10 Oct 2021 20:35:05 GMT</pubDate>
            <atom:updated>2022-02-14T09:07:53.327Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kAQazkEpTN43dkzNbjBWg.png" /><figcaption>image from <a href="https://wallpaperbat.com/">wallpaperbat.com</a></figcaption></figure><h3>Leveling Up Your JavaScript (Part 1)</h3><p>Following my previous article <a href="https://medium.com/geekculture/writing-clean-javascript-es6-edition-834e83abc746">Writing Clean JavaScript</a>, I’ve decided to take a step further and discuss rather advanced <strong>JavaScript </strong>concepts that proved useful in my career.</p><p>The concepts I will discuss are fundamental to the language and will stay there regardless of the framework you use. Moreover, having a good grasp of these concepts will be invaluable when you decide to learn or use a popular JavaScript library or framework.</p><p>This is the first part of a two-part series where I cover several important concepts you should master to advance your JavaScript skills.</p><h3>1. What is ‘this’?</h3><p>If you already have some experience with other languages like C++ or Java, you may have dealt with this keyword, or perhaps self for Python. For these languages, this refers to the instance of the current object when called in a method of a class.</p><p>JavaScript, however, uses this somehow differently: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a> keyword can be used outside the context of a function or a method — namely in the global context, and it will have different behavior based on which mode is used.</p><h4>Global Context</h4><p>The global context is simply the <a href="https://developer.mozilla.org/en-US/docs/Glossary/Global_object">Global Object</a>, which is defined as the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">window</a> object in the browser, or the <a href="https://nodejs.org/api/globals.html#globals_global">global</a> object in Node JS. Regardless of whether “strict” or “non-strict” mode is used, this will always behave the same in the global context.</p><p>For example, the following is valid in any browser:</p><pre>console.log(this === window) // true</pre><pre>this.foo = &quot;This is a global variable&quot;<br>console.log(window.foo) // This is a global variable</pre><h4>Function Context</h4><p>Inside a function, the behavior of this is determined by the way the function is invoked, and the mode used.</p><p>In JavaScript, a function can be invoked in 4 different ways. In the following examples, I will show how this behaves for each case:</p><p><strong>i. Simple Function Invocation</strong></p><p>In “non-strict” mode, this will reference the global object when the function is called. However, in “strict” mode this will be set to undefined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1280dcdfa9834a496f00bf24304d7c1a/href">https://medium.com/media/1280dcdfa9834a496f00bf24304d7c1a/href</a></iframe><p><strong>ii. Method Invocation</strong></p><p>Inside a method of an object, this will simply reference the containing object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94f9df5bbcb5906db74dcea17aa634bf/href">https://medium.com/media/94f9df5bbcb5906db74dcea17aa634bf/href</a></iframe><p>But what if we store getCountry in another variable?</p><pre>const getCountry = address.getCountry;</pre><p>Assuming code is executed in a browser using “non-strict” mode, this will fallback to window. Thus, getCountry() will evaluate to window.country because the parent object is not specified in this case:</p><pre>console.log(getCountry()); // undefined</pre><p>This is why we should use<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind">Function.prototype.bind</a> . The bind method, as the name suggests, will <em>bind</em> a new object to the specified function, exposing the object’s this .</p><pre>const getCountry = address.getCountry.bind({ country: &quot;USA&quot; });<br>console.log(getCountry()); // USA</pre><p><strong>iii. Constructor Invocation</strong></p><p>A function can be used as a constructor when initialized with the new keyword. When the new keyword is used, a new object is initialized with this referencing it. Omitting the new keyword will set this to the fallback global value and cause errors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71b2fe8da4c233d620529acee92a1554/href">https://medium.com/media/71b2fe8da4c233d620529acee92a1554/href</a></iframe><p>To prevent such behavior, extra handling should be added to the constructor function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4de7a8755db19cbf73e04564ac6a304e/href">https://medium.com/media/4de7a8755db19cbf73e04564ac6a304e/href</a></iframe><p>More on this will be covered in the <a href="#48b9">Prototypes section</a>.</p><p><strong>iv. Indirect Invocation</strong></p><p>JavaScript functions support referencing other objects via this keyword when they are invoked. We can achieve this behavior by using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">Function.prototype.call</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">Function.prototype.apply</a>. Both call and apply do exactly the same thing. The only difference is that call expects an object and as many arguments as needed, while apply expects all the arguments — besides the object — to be passed as an array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b66c7582ec0737d344a11e2ceb235387/href">https://medium.com/media/b66c7582ec0737d344a11e2ceb235387/href</a></iframe><blockquote>Finally, note that <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">ES6 Arrow Functions</a> do not have their own execution context, but rather inherit this from their outer parent. This is the reason why we cannot use arrow functions to define function or class methods.</blockquote><p>For more detailed examples on this check <a href="https://www.javascripttutorial.net/javascript-this/">this article</a>.</p><h3>2. Prototypes</h3><p>All JavaScript objects inherit properties and methods from a <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">prototype</a>. Prototypes allow us to add methods and properties to our objects, and inherit features from one another.</p><p>When using the previously introduced constructor invocation, we will notice the JavaScript will add the <em>prototype property</em> to our object, which points to the original constructor:</p><pre>function Person(name, age) {<br>  this.name = name;<br>  this.age = age;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*vLoU96OxpEvvV48DWA-vVA.png" /></figure><p>We can add a method to our original constructor to get the year of birth. After adding this method, all objects having Person as their <em>prototype object </em>will<em> inherit</em> this method:</p><pre>Person.prototype.getYearOfBirth = function () {<br>  return new Date().getFullYear() - this.age;<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*AJTjuLmZumDffbtxthXLmw.png" /></figure><p>Using the same procedure, we can add or modify methods and properties of existing JavaScript prototype objects such as Array.prototype or Date.prototype, however, this is generally not advisable.</p><p>I will not cover any additional material on prototypes, but you can always <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">check the docs</a> for advanced concepts.</p><h3>3. Classes</h3><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">ES6 classes</a> are just special functions built over JavaScript prototype-based inheritance. This is why JavaScript classes are always referred to as “syntactic sugar”. These classes do not provide additional features found in other OOP languages such as object-oriented inheritance, however, they serve as a good template to construct objects.</p><p>This is how we can implement a class similar to our previous prototype object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce1c9070a124d8d9b3921cfde30b0929/href">https://medium.com/media/ce1c9070a124d8d9b3921cfde30b0929/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*IKPnRTja3Cug_5LG4GYa2g.png" /></figure><p>Generally, ES6 classes merely provide cleaner syntax to regular prototype objects to resemble classes in other languages such as Java and C++, without adding any OOP features.</p><h3>4. Scopes</h3><p>A <a href="https://developer.mozilla.org/en-US/docs/Glossary/Scope">scope</a> in JavaScript defines how values and functions can be accessed throughout code. By definition, all scopes in JavaScript can be described as <strong>global</strong> or <strong>local.</strong></p><h4>Global Scope</h4><p>In simple terms, everything defined outside all functions and curly braces {} belongs to the global scope. Variables defined within the global scope can be used anywhere in the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a91873f835416299938094dd9917b23a/href">https://medium.com/media/a91873f835416299938094dd9917b23a/href</a></iframe><p>Generally, you want to limit the number of global variables as much as possible because:</p><ul><li>Using global variables might cause naming collisions as code scales. Note that redeclaring const or let variables will throw an error, while redeclaring var will override the variable.</li><li>In browsers, global variables are members of the window object which is accessible by users and any script running on the page. Hence, using global values might introduce security issues.</li><li>JavaScript performs variable lookups starting from the current scope and going up to the next parent until reaching the global scope. Having many global variables might result in performance issues.</li></ul><h4>Local Scope</h4><p>Local scope is the scope for local variables. The local scope consists of <strong>function</strong> and <strong>block</strong> scopes.</p><ul><li><strong>Function Scope</strong></li></ul><p>Variables declared inside a function are only accessible within the same function. This rule applies for variables declared using var, let or const:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1e42c779d29f4612e04e4762c6d0d17/href">https://medium.com/media/d1e42c779d29f4612e04e4762c6d0d17/href</a></iframe><ul><li><strong>Block Scope</strong></li></ul><p>Introduced in ES6, variables that are declared using const or let within any curly brace {} have block scope, meaning they are only accessible inside the same block. Block scope is in fact a subset of function scope — <em>except for the case of arrow functions with implicit returns</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d36fd68ea6e0d0379c7b32068a4e824/href">https://medium.com/media/7d36fd68ea6e0d0379c7b32068a4e824/href</a></iframe><h3>5. Hoisting</h3><p>In JavaScript, hoisting is the default process of moving variable and function declarations to the top of the current scope before code execution. This technically means that you can use variables before they are declared.</p><pre>foo = &quot;Variable to declare later&quot;;<br>console.log(foo); <em>// Variable to declare later<br></em>var foo;</pre><p>It is important to know that only declarations are moved to the top but not initializations:</p><pre>console.log(foo); <em>// undefined<br></em>var foo = &quot;Variable initialized later&quot;;</pre><p>Here, the declaration of foo is moved to the top, but since it’s only initialized later, it will first hold the value undefined.</p><h4>Block scope and hoisting</h4><p>As discussed earlier, const and let are block-scoped. The block is “<em>aware</em>” of these variables but cannot use them before they are declared. Values declared with const and let are said to be in a “<em>temporal dead zone” </em>until declared.</p><p>Initializing let before declaring will throw a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError">ReferenceError</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*erBsqn0NPHi4l4lvd1QNrg.png" /></figure><p>However, Initializing const before declaring will throw a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a>, so code will not even run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*O9sLkvuRELQ9xhZlhWYdDQ.png" /></figure><h4>Function Hoisting</h4><p>When using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function">function declaration</a>, functions will be hoisted to the top of the current scope. This means you can use a function before it is declared.</p><p>In contrast, if you use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a>, functions won’t be hoisted, so you need to use the function only after it is declared:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91b4ffd0b2ce2b3385690ea176a19de0/href">https://medium.com/media/91b4ffd0b2ce2b3385690ea176a19de0/href</a></iframe><h3>6. Closure</h3><p>The definition of a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">closure</a> from the spec is:</p><blockquote>The combination of a function and the lexical environment within which that function was declared.</blockquote><p>In other words, a closure is an inner function that can access the variables of its enclosing or outer function. We can hence conclude that a closure has three scope chains:</p><ul><li>Access to its own <strong>block scope</strong></li><li>Access to the <strong>scope of its enclosing function </strong>(or outer function)</li><li>Access to the <strong>global scope</strong></li></ul><p>Consider the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/152fdf6cd012a679377a93d264fd0b6a/href">https://medium.com/media/152fdf6cd012a679377a93d264fd0b6a/href</a></iframe><p>In the following example, we can see how we can have nested closures, each having access to all variables of their enclosing functions, their local variables, and global variables. I used timeouts here to demonstrate the most important feature of closures:</p><blockquote>An inner function will still have access to values from its outer function even if the outer function has already returned.</blockquote><h3>7. Currying</h3><p>The concept of <strong>closure</strong> in JavaScript enables us to benefit from <strong>currying</strong> which is<em> an important functional programming concept</em>.</p><blockquote>Currying is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c)</blockquote><p>In other words, a curried function will not return a value once you pass an argument. Instead, this function will keep returning a new function expecting the next argument in the set until all arguments are exhausted. The result of all functions will be returned once the final argument is passed. Following is the implementation of an addition function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a56adef88fff8860728438947c66c685/href">https://medium.com/media/a56adef88fff8860728438947c66c685/href</a></iframe><p>A more realistic use-case of currying would be implementing event handlers with predefined arguments. Take the following trivial React component as an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e2a9c464982fa69c86b8953973e33fb/href">https://medium.com/media/8e2a9c464982fa69c86b8953973e33fb/href</a></iframe><p>In this case, an alert will only pop when clicking on a button. The alert message will be the same message passed when the curried function was called the first time — thanks to closure.</p><p>You can check <a href="https://javascript.info/currying-partials">this article</a> for a better understanding of currying and its use-cases.</p><h3>8. IIFE</h3><p>An <a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">IIFE (Immediately Invoked Function Expression)</a> is a function that is invoked as soon as it’s defined. IIFEs are important since all variables declared inside these functions cannot be accessed by the outer scope. In general, you are most likely to use these functions when you want to directly execute some code and guarantee data privacy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fa61dc8ff6de71070432dedf3ccc07c/href">https://medium.com/media/3fa61dc8ff6de71070432dedf3ccc07c/href</a></iframe><p>An important use-case would be utilizing IIFEs and JavaScript’s <a href="https://javascript.plainenglish.io/data-hiding-with-javascript-module-pattern-62b71520bddd">Module Pattern</a> to implement a <strong>Singleton</strong> object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95b3c4d89cb6932a2abd935bb104c2b2/href">https://medium.com/media/95b3c4d89cb6932a2abd935bb104c2b2/href</a></iframe><p>Later on, we will have access to only one instance when we import our singleton object somewhere else:</p><pre>import MySingletonDAO from &quot;./MyDAO&quot;</pre><pre>const instance1 = MySingletonDAO.getInstance()<br>const instance2 = MySingletonDAO.getInstance()</pre><pre>console.log(instance1 === instance2) // true</pre><p>In this part, I briefly discussed several concepts you need to master to advance your JavaScript skills. In the next part, I will focus more on other important subjects such as asynchronous functions and iterators. I hope you enjoyed your reading and see you then!</p><figure><a href="http://buymeacoffee.com/jalkhurfan"><img alt="" src="https://cdn-images-1.medium.com/max/260/1*gzdOEDskvMA1wW6CUF3RkA.png" /></a><figcaption>Support me to write more!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13447e30980" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/leveling-up-your-javascript-part-1-es6-edition-13447e30980">Leveling Up Your JavaScript (Part 1) — ES6 Edition</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manipulating Arrays in JavaScript]]></title>
            <link>https://medium.com/geekculture/manipulating-arrays-in-javascript-dc07045d3dce?source=rss-6f040e113bce------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc07045d3dce</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Jihad Al Khurfan]]></dc:creator>
            <pubDate>Sun, 29 Aug 2021 21:16:35 GMT</pubDate>
            <atom:updated>2022-01-23T09:04:54.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCPNNcF9l8nliSJdVxNIGw.jpeg" /><figcaption>Image by Fojan Babaali</figcaption></figure><p><strong>Data manipulation</strong> essentially means adjusting data to make it easier to read, understand and use. Whether you’re rendering UI, fetching data from an API, or reading from files, you will have to manipulate data in all sorts of <strong>JavaScript</strong> applications.</p><p>If you’ve worked enough on JavaScript projects, you’ll notice that it’s very common to see data in the form of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">arrays</a>. Surely there are tons of resources covering JavaScript arrays out there, and anyone reading this article <em>probably knows how to perform basic operations on arrays. </em>Nevertheless, the main purpose of this article is to introduce you to different JavaScript array methods and practices that can be utilized to achieve <a href="https://medium.com/geekculture/writing-clean-javascript-es6-edition-834e83abc746">simpler and cleaner code</a>.</p><h3>Starting with the basics</h3><p>In this section, I will briefly mention some of the common static and instance array methods used to create, access, or mutate arrays. The content of this section might sound very basic or high-level for most readers, yet, it is important to cover it before diving deeper into more advanced topics.</p><blockquote>If you’re comfortable with the following concepts, skip to the next section!</blockquote><h4>Static methods</h4><p>These methods are used to create new arrays or convert existing iterable and array-like objects to arrays.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82d66cb32dfc278d60cef864662db5ce/href">https://medium.com/media/82d66cb32dfc278d60cef864662db5ce/href</a></iframe><h4>Mutation methods</h4><p>The following methods are instance methods or prototypal methods. They are called on a specific array instance to apply mutations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a1b07ae99ccaa1801c000f47440fd22/href">https://medium.com/media/3a1b07ae99ccaa1801c000f47440fd22/href</a></iframe><p><strong>Other instance methods</strong></p><p>These are other pure instance methods that won’t mutate the array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c14f42585a7749b3fa6508dfed3f98a4/href">https://medium.com/media/c14f42585a7749b3fa6508dfed3f98a4/href</a></iframe><h3>Questioning traditional loops</h3><p>When thinking about arrays, iteration is usually the first word that pops in mind. We iterate over arrays to apply the same logic <em>for each</em> value. At this point, it might seem that anything we want to apply to array members can be achieved using a traditional loop with all its variants (i.e for, for-of, and .forEach() loops).</p><p>Here are some examples where using traditional loops is perfectly fine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/539f1fbdb2a743388b450674e278030d/href">https://medium.com/media/539f1fbdb2a743388b450674e278030d/href</a></iframe><p>But what if we need to do more than that, maybe modify or filter array elements? We can for sure use traditional loops, but can’t we do any better?</p><p>In the following section, I will present better alternatives to traditional loops in which each alternative will be compared to the .forEach() method for simplicity.</p><p>For the following examples, we will use this data set as reference:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/739bf98026746ae575caa1a0dbeda5a3/href">https://medium.com/media/739bf98026746ae575caa1a0dbeda5a3/href</a></iframe><blockquote>Note that I will be heavily using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>arrow functions with implicit returns</em></a> for readability, in case you’re not familiar.</blockquote><h3>Replacing traditional loops</h3><h4>.map()</h4><p>As the name suggests, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">Array.protoype.map()</a> maps the elements of the current array to a new array after applying some logic on each element. Let’s say you’ve received the previous cart data which includes UTC timestamps and prices (as numbers), and that you need to localize your data based on the user’s browser settings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd56ac241c82f3ef1dec74416773674c/href">https://medium.com/media/cd56ac241c82f3ef1dec74416773674c/href</a></iframe><p>As you can see, the use of .map()saves us from creating an empty array and pushing each modified element into it by providing a much elegant solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_DUykiIKioQa0TqT0hNlA.png" /></figure><h4>.filter()</h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">Array.prototype.filter()</a> is another method that returns a new array of elements each satisfying the provided test condition. Using the same cart data, imagine we wanted to filter all elements that have a price greater than or equal to $15.00:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76d61cc05b693d027bb41d4265b106d3/href">https://medium.com/media/76d61cc05b693d027bb41d4265b106d3/href</a></iframe><p>The expected result will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jiIbXyhcxu0E0QcsHiVueQ.png" /></figure><h4>.find() &amp; .findIndex()</h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find">Array.prototype.find()</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex">Array.prototype.findIndex()</a> are pretty self-explanatory. The first method returns the value of the first element that satisfies a given test condition, while the second returns the index of this element. In the following example, we are interested in finding the index and the value of the first element whose quantity is less than 2:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/672cd1182c64d7f67914ca370f86f883/href">https://medium.com/media/672cd1182c64d7f67914ca370f86f883/href</a></iframe><p>The results are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIgNHELTWMfN7oUrhw5Nlw.png" /></figure><h4>.reduce()</h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">Array.prototype.reduce()</a> is a very useful method that applies some logic to each iteration while accumulating results of all previous iterations. In this context, the “accumulator” could be a new object, array, or a simple variable. In this example, we are interested in calculating the total price of all cart items:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55d6bf4b277f665d5480231043594ebf/href">https://medium.com/media/55d6bf4b277f665d5480231043594ebf/href</a></iframe><p>And the result of our reducer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7x9udTU15TQGUtUePWYVpA.png" /></figure><blockquote>Obviously, .reduce() has much powerful use-cases than computing sums, however, I chose to keep examples simple in this article to cover as much concepts as possible.</blockquote><h4>.every() &amp; .some()</h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every">Array.prototype.every()</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some">Array.prototype.some()</a> check if <strong>every</strong> or <strong>some</strong> elements satisfy a test condition <em>respectively</em>. These methods should be used instead of .filter() and .find()— and obviously traditional loops — whenever you’re only interested in a “<em>Yes or No</em>” answer rather than the actual values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/107f0ad9728ca55d6978cc03ad2b2f4a/href">https://medium.com/media/107f0ad9728ca55d6978cc03ad2b2f4a/href</a></iframe><h4>.sort()</h4><p>The last method to cover in this section is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">Array.prototype.sort()</a> which takes a comparator function as an argument and returns a sorted array. The default sort order is ascending when no custom comparator is provided.</p><h4>Chaining methods</h4><p>Now that we have seen different practices of array methods, let’s use them together. Suppose you had to modify the cart array to satisfy the following constraints:</p><ul><li>All items should be marked as available</li><li>We only want to present itemIdand netPrice</li><li>Items should be sorted in ascending order of quantities</li></ul><p>We can easily achieve all the constraints by chaining array methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5618e4022f1e6266d6fcb4a5b5f1b251/href">https://medium.com/media/5618e4022f1e6266d6fcb4a5b5f1b251/href</a></iframe><blockquote>Keep in mind that over-chaining might increase time complexity and affect performance, so make sure you optimize these calls.</blockquote><h3>Bonus: Using ES6 features</h3><h4>Destructuring</h4><pre>const [apple, banana, cherries] = [&quot;🍏&quot;, &quot;🍌&quot;, &quot;🍒&quot;];</pre><pre>console.log(apple); <em>// 🍏<br></em>console.log(banana); <em>// 🍌<br></em>console.log(cherries); <em>// 🍒</em></pre><h4>Default values</h4><pre>const [apple, banana, cherries, mango = &quot;🥭&quot;] = [&quot;🍏&quot;, &quot;🍌&quot;, &quot;🍒&quot;];</pre><pre>console.log(mango); <em>// 🥭</em></pre><h4>Skipping values</h4><pre>const [apple, , cherries] = [&quot;🍏&quot;, &quot;🍌&quot;, &quot;🍒&quot;];</pre><pre>console.log(apple); <em>// 🍏<br></em>console.log(cherries); <em>// 🍒</em></pre><h4>Spread operator</h4><pre>const [apple, ...others] = [&quot;🍏&quot;, &quot;🍌&quot;, &quot;🍒&quot;];</pre><pre>console.log(apple); <em>// 🍏<br></em>console.log(others); <em>// [&quot;🍌&quot;, &quot;🍒&quot;]</em></pre><p>This was a comprehensive guide on using proper array methods for data manipulation. I definitely didn&#39;t cover everything, but I made sure I mentioned the most commonly used methods. If you found this article useful, you might as well like<a href="https://medium.com/geekculture/writing-clean-javascript-es6-edition-834e83abc746"> my previous article</a>.</p><figure><a href="http://buymeacoffee.com/jalkhurfan"><img alt="" src="https://cdn-images-1.medium.com/max/260/1*gzdOEDskvMA1wW6CUF3RkA.png" /></a><figcaption>Support me to write more!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc07045d3dce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/manipulating-arrays-in-javascript-dc07045d3dce">Manipulating Arrays in JavaScript</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Clean JavaScript —  ES6 Edition]]></title>
            <link>https://medium.com/geekculture/writing-clean-javascript-es6-edition-834e83abc746?source=rss-6f040e113bce------2</link>
            <guid isPermaLink="false">https://medium.com/p/834e83abc746</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Jihad Al Khurfan]]></dc:creator>
            <pubDate>Mon, 23 Aug 2021 08:41:34 GMT</pubDate>
            <atom:updated>2022-02-14T09:05:11.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGllHv3pophTVibKQbIbzg.jpeg" /><figcaption>Photo by <a href="https://dribbble.com/redaco">Redaco</a> on <a href="https://dribbble.com/">dribbble</a></figcaption></figure><h3>Writing Clean JavaScript</h3><p>Clean code is not just code that works, but rather code that can be easily read, reused, and refactored by others. Writing clean code is important because, in a typical work environment, you are not writing for yourself or for the machine. In reality, you are writing for a group of developers who will need to understand, edit and build over your work.</p><p>This article focuses on writing clean<strong> JavaScript </strong>code which is <em>not framework-specific</em>, nonetheless, most of the mentioned examples can apply to <em>almost any other programming language</em>. In general, the following concepts are recommendations mostly adopted from Robert C. Martin’s book <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"><em>Clean Code</em></a>,<em> </em>and they are not meant to be strictly followed.</p><h3>1. Variables</h3><h4>Use meaningful names</h4><p>Names of variables should be descriptive. The rule of thumb is that most JavaScript variables are in Camel Case (<em>camelCase</em>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86f0ce7c4860aa46139ad09843d2ffc3/href">https://medium.com/media/86f0ce7c4860aa46139ad09843d2ffc3/href</a></iframe><p>Note that boolean names usually answer specific questions, for example:</p><pre>isActive<br>didSubscribe<br>hasLinkedAccount</pre><h4>Avoid adding unnecessary contexts</h4><p>Do not add redundant context to variable names when the context is already provided by the containing object or class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8fadd884ae8fa5a5d11967fcda29f8d/href">https://medium.com/media/c8fadd884ae8fa5a5d11967fcda29f8d/href</a></iframe><h4>Avoid hardcoded values</h4><p>Instead of plugging in constant values, make sure to declare meaningful and searchable constants. Notice that global constants can be stylized in Screaming Snake Case (<em>SCREAMING_SNAKE_CASE</em>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc8680bb2b391154742cedac2e561ad2/href">https://medium.com/media/bc8680bb2b391154742cedac2e561ad2/href</a></iframe><h3>2. Functions</h3><h4>Use descriptive names</h4><p>Function names can be lengthy, as long as they portray what the function actually does. Function names usually have the form of action verbs, with the possible exception of functions that return booleans — which can have the form of a “<em>Yes or No</em>” question. Function names should also be in Camel Case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afc2acbcb7fde50724c5f9b64bb2d03e/href">https://medium.com/media/afc2acbcb7fde50724c5f9b64bb2d03e/href</a></iframe><h4>Use default arguments</h4><p>Default arguments are cleaner than short-circuiting or using extra conditional statements inside the function body. Though, it is important here to remember that short-circuiting works for all values that are considered “<em>falsy</em>”<em> </em>such as false, null, undefined, &#39;&#39;, &quot;&quot;, 0, and NaN, while default arguments only replace undefined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84a951d4a930c3af4e2456341f9bdce4/href">https://medium.com/media/84a951d4a930c3af4e2456341f9bdce4/href</a></iframe><h4>Limit the number of arguments</h4><p>As controversial as this rule might be, functions should have 0, 1, or 2 arguments. Having three arguments is already excessive, and beyond that implies either of two cases:</p><ul><li>The function is already doing a lot and should be divided.</li><li>The data passed to the function is somehow related and can be passed as a dedicated data structure.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1afe2af5f7f90e8e9ab95831a6f9d65/href">https://medium.com/media/d1afe2af5f7f90e8e9ab95831a6f9d65/href</a></iframe><h4>Avoid executing multiple actions in a function</h4><p>A function should do one thing at a time. This rule helps reduce the function’s size and complexity, which results in easier testing, debugging, and refactoring. The number of lines in a function is a strong indicator that should raise a flag on whether the function is doing many actions. Generally, try aiming for something less than 20–30 lines of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f558ceee0405c17371ea96401cdb42d9/href">https://medium.com/media/f558ceee0405c17371ea96401cdb42d9/href</a></iframe><h4>Avoid using flags as arguments</h4><p>A flag in one of the arguments effectively means the function can still be simplified.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd9a79b6bff44d6094114295be60342a/href">https://medium.com/media/fd9a79b6bff44d6094114295be60342a/href</a></iframe><h4>Do not repeat yourself (DRY)</h4><p>Duplicate code is never a good sign. If you repeat yourself you will have to update multiple places whenever there is a change in logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9840ce71b49c442c170d82cebd01738/href">https://medium.com/media/f9840ce71b49c442c170d82cebd01738/href</a></iframe><h4>Avoid side effects</h4><p>In JavaScript, you should favor functional over imperative patterns. In other words, keep functions pure unless needed otherwise. Side effects can modify shared states and resources, resulting in undesired behaviors. All side effects should be centralized; if you need to mutate a global value or modify a file, dedicate one and only one service for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dff1a48dbe0b6e9c966b150063559bb7/href">https://medium.com/media/dff1a48dbe0b6e9c966b150063559bb7/href</a></iframe><p>Moreover, if a mutable value is passed to a function, you should return a new mutated clone of the value rather than mutating the value directly and returning it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9ea07b8c24a8850eeb90c37e4f74901/href">https://medium.com/media/b9ea07b8c24a8850eeb90c37e4f74901/href</a></iframe><h3>3. Conditionals</h3><h4>Use non-negative conditionals</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f10f36739edfdfab0065cc330fc980ff/href">https://medium.com/media/f10f36739edfdfab0065cc330fc980ff/href</a></iframe><h4>Use shorthands whenever possible</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a88352b288a21c89f99a9598e5bd16a6/href">https://medium.com/media/a88352b288a21c89f99a9598e5bd16a6/href</a></iframe><h4>Avoid branching and return soon</h4><p>Returning early will make your code linear, more readable, and less complex.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56e425d6d86b34c18a0f4716116b1fe1/href">https://medium.com/media/56e425d6d86b34c18a0f4716116b1fe1/href</a></iframe><h4>Favor object literals or maps over switch statements</h4><p>Whenever this applies, indexing using objects or maps will reduce code and improve performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a5095699acb8cc55b4e555271bcc7da/href">https://medium.com/media/4a5095699acb8cc55b4e555271bcc7da/href</a></iframe><h4>Use optional chaining</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/736c40963fb978d7affb4c8a052ca97f/href">https://medium.com/media/736c40963fb978d7affb4c8a052ca97f/href</a></iframe><h3>4. Concurrency</h3><h4>Avoid callbacks</h4><p><a href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">Callbacks</a> are messy and result in nested code. <a href="https://www.w3schools.com/js/js_es6.asp">ES6</a> offers <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a> which allow for chaining callbacks and thus result in cleaner code. Yet, <a href="https://262.ecma-international.org/8.0/">ECMAScript 2017</a> also provides the “<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">Async/Await</a>” syntax as an arguably cleaner solution that imposes further linearity to code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34ed25535476e8825d535d5e1948f04a/href">https://medium.com/media/34ed25535476e8825d535d5e1948f04a/href</a></iframe><h3>5. Error Handling</h3><h4>Handle thrown errors and rejected promises</h4><p>No need to mention why this is an extremely important rule. Spending time now on handling errors correctly will reduce the likelihood of having to hunt down bugs later, especially when your code reaches production.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0863e7e4854d39123dc9231fe2d3781c/href">https://medium.com/media/0863e7e4854d39123dc9231fe2d3781c/href</a></iframe><h3>6. Comments</h3><h4>Only comment business logic</h4><p>Readable code saves you from over-commenting your code. Hence, you should only comment on complex logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f633ace11bbef4bdda2c3d1ff036bb6/href">https://medium.com/media/1f633ace11bbef4bdda2c3d1ff036bb6/href</a></iframe><h4>Make use of version control</h4><p>There is absolutely no reason to keep commented code or journal comments, version control is already there to handle this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62e62df305f91f4911e1f931bc0d5817/href">https://medium.com/media/62e62df305f91f4911e1f931bc0d5817/href</a></iframe><h4>Document when possible</h4><p>Documentation helps increase code quality and reliability. It serves as a user manual for your codebase in which anyone understands all the aspects of your code.</p><pre>/**  <br> * Returns x raised to the n-th power.  <br> *  <br> * @param {number} x The number to raise.  <br> * @param {number} n The power, should be a natural number.  <br> * @return {number} x raised to the n-th power.  <br> */ <br>function pow(x, n) {   <br>    // ...<br>}</pre><p>This article discussed briefly some important steps that can be taken to increase your JavaScript code using latest syntax. Again, most of these concepts can be generalized and applied to different programming languages. Adopting these practices can take some time especially for larger codebases, but will guarantee that — for the long run — your code becomes readable, scalable, and easy to refactor.</p><figure><a href="http://buymeacoffee.com/jalkhurfan"><img alt="" src="https://cdn-images-1.medium.com/max/260/1*gzdOEDskvMA1wW6CUF3RkA.png" /></a><figcaption>Support me to write more!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=834e83abc746" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/writing-clean-javascript-es6-edition-834e83abc746">Writing Clean JavaScript —  ES6 Edition</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>