<?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 Glad Chinda on Medium]]></title>
        <description><![CDATA[Stories by Glad Chinda on Medium]]></description>
        <link>https://medium.com/@gladchinda?source=rss-ddcd0e9719e5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K5myVh5FXG5SWb-VzPcgJA.png</url>
            <title>Stories by Glad Chinda on Medium</title>
            <link>https://medium.com/@gladchinda?source=rss-ddcd0e9719e5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 17 Jun 2026 23:49:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gladchinda/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[JavaScript Type Casting Gone Wrong]]></title>
            <link>https://medium.com/bitsrc/javascript-type-casting-gone-wrong-53e59ebee9f9?source=rss-ddcd0e9719e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/53e59ebee9f9</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Glad Chinda]]></dc:creator>
            <pubDate>Tue, 04 Aug 2020 18:46:03 GMT</pubDate>
            <atom:updated>2020-10-26T15:31:12.269Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide for safely casting JavaScript values to strings.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xe2wxwY9Csk3Z3Wv-OdA0A.jpeg" /></figure><h3>TL;DR</h3><p>Until recently, I always thought that when casting any JavaScript value to a string, both String(somevar) and &quot;&quot; + somevar were equivalent. Well, they are not, and I have been wrong all along.</p><pre><strong>const symbol = Symbol();</strong></pre><pre><strong>console.log(String(symbol)); // “Symbol()”</strong></pre><pre>// For string concatenation involving a symbol,<br><strong>// throws a TypeError exception.</strong><br><strong>console.log(&quot;&quot; + symbol);</strong></pre><p>If it is any consolation, they both produce the same result for most JavaScript values. However, it’s possible to create custom JavaScript objects for which they differ in results.</p><blockquote><strong>Continue reading to find out more…</strong></blockquote><h3>Background</h3><p>The majority of programming languages out there provide mechanisms for converting between value types either implicitly (<em>type coercion</em>) or explicitly (<em>type casting</em>), of which JavaScript is not an exception.</p><p>There are times when the JavaScript engine needs a value to be of a certain type before it can be able to carry out some operations on it. In such cases, the JavaScript engine implicitly <em>coerces</em> the value to the required type.</p><p>However, type conversions can be done explicitly in code. The following example shows how to explicitly cast a JavaScript value to its boolean equivalent (the result depends on whether the value is <em>truthy</em> or <em>falsy</em>):</p><pre>// Using the global Boolean function<br><strong>var boolean = Boolean(value);</strong></pre><pre>// Using the double-NOT(!!) trick<br><strong>var boolean = !!value;</strong></pre><blockquote>From this point going forward, more emphasis will be laid on explicitly casting JavaScript values to strings.</blockquote><h3>Type Casting (To String)</h3><p>Just as we saw earlier with casting values to booleans, similar approaches can be taken to cast JavaScript values to strings.</p><pre>// Using the global String function<br><strong>var string = String(value);</strong></pre><pre>// Using string concatenation(+) with empty string<br><strong>var string = &quot;&quot; + value;</strong></pre><blockquote>For a long time, I have always thought that both approaches for casting to a string will produce the same string for any JavaScript value. And guess what? I have been wrong all along, and not just me alone, as we will find out shortly.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F8HqjtoyKrnfJC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F8HqjtoyKrnfJC%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F8HqjtoyKrnfJC%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff0a4280854a8042c45dddd515cf6d90/href">https://medium.com/media/ff0a4280854a8042c45dddd515cf6d90/href</a></iframe><p>The first obvious difference between the two casting approaches can be seen with JavaScript symbols. Using the global String() function will return the symbol’s <em>descriptive string</em>, while string concatenation will throw a <strong>TypeError</strong> exception.</p><pre><strong>const symbol = Symbol();</strong></pre><pre><strong>console.log(String(symbol)); // “Symbol()”</strong></pre><pre>// For string concatenation involving a symbol,<br><strong>// throws a TypeError exception.<br>console.log(&quot;&quot; + symbol);</strong></pre><h3>Case Study</h3><p>For most JavaScript values and objects, both approaches will produce the same string result. However, it is very possible to create custom JavaScript objects for which they differ in results.</p><p>Consider the following code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f66a32dac6ac02215a5f56ad58c0a0d0/href">https://medium.com/media/f66a32dac6ac02215a5f56ad58c0a0d0/href</a></iframe><p>The createSalaryObject() function returns a custom JavaScript object that defines its own valueOf and toString methods. Also, casting the salary object to a string using the two approaches produced different results.</p><h3>Why the Difference</h3><p>To understand the reason for the difference between the two approaches, we need to first understand how they work (as described in the ECMAScript Language specification).</p><h4>String(value)</h4><ul><li>If value is not specified, return an empty string.</li><li>If value is a symbol, return the symbol’s descriptive string — for example: &quot;Symbol(description)&quot;.</li><li>Else, return the result of the abstract operation <strong>ToString(</strong><em>value</em><strong>)</strong>.</li></ul><p>Here is how the <strong>ToString(</strong><strong><em>argument</em></strong><strong>)</strong> abstract operation works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9R5rAG9-jrjjOa81Q6X_g.png" /></figure><p>Now let’s apply all we’ve seen above to the salary object we saw in the code snippet from before:</p><pre>// Since `salary` is an object<br><strong>String(salary) =&gt; ToString(salary)</strong></pre><pre>// Also, because `salary` is of type object<br><strong>ToString(salary) =&gt; ToString(ToPrimitive(salary, hint = string))</strong></pre><pre>// Therefore we can say:<br><strong>String(salary) =&gt; ToString(ToPrimitive(salary, hint = string))</strong></pre><h4>” ” + value</h4><ol><li>Convert both operands to primitive values using the <strong>ToPrimitive(</strong><em>value</em><strong>)</strong> abstract operation.</li><li>If any of the primitives from (1) above is a string, convert both primitives to strings using the <strong>ToString(</strong><em>primitive</em><strong>)</strong> abstract operation.</li><li>If there are no errors so far, return the result of concatenating both strings from (2) above.</li></ol><p>Now let’s apply all we’ve seen above to the salary object we saw in the code snippet from before:</p><pre>// First converting operands to primitives<br><strong>&quot;&quot; + salary =&gt; ToPrimitive(&quot;&quot;) + ToPrimitive(salary)</strong></pre><pre>// Because ToPrimitive(&quot;&quot;) =&gt; &quot;&quot; (which is a string),<br>// the above becomes:<br><strong>&quot;&quot; + salary =&gt; ToString(&quot;&quot;) + ToString(ToPrimitive(salary))</strong></pre><pre>// Since ToString(&quot;&quot;) =&gt; &quot;&quot;,<br>// we can further simplify the above to:<br><strong>&quot;&quot; + salary =&gt; &quot;&quot; + ToString(ToPrimitive(salary))</strong></pre><pre>// Since one of the operands is an empty string,<br>// it is safe to say that the string concatenation will<br>// return the other operand:<br><strong>&quot;&quot; + salary =&gt; ToString(ToPrimitive(salary))</strong></pre><h4>The Difference</h4><p>If we compare the outcomes of both approaches, we will notice that the difference results from the <strong>ToPrimitive</strong> abstract operation.</p><pre>// ToPrimitive (with string hint)<br><strong>String(salary) =&gt; ToString(ToPrimitive(salary, hint = string))</strong></pre><pre>// ToPrimitive (without hint)<br><strong>&quot;&quot; + salary =&gt; ToString(ToPrimitive(salary))</strong></pre><blockquote>For <strong><em>String(value)</em></strong>, the <strong><em>ToPrimitive</em></strong> operation is carried out with the <strong><em>string</em></strong> hint. While for <strong><em>&quot;&quot; + value</em></strong>, the operation is done without hint. Except for JavaScript symbols (which we have seen already), therein lies the difference between the two approaches.</blockquote><p>This difference can only manifest itself, if the value being cast is some kind of custom JavaScript object, just like our salary object.</p><p>Now that we know where the difference comes from, let’s examine how the <strong>ToPrimitive</strong> abstract operation handles hints.</p><h4>The ToPrimitive Operation</h4><p>The <strong>ToPrimitive</strong> abstract operation has <strong>three possible hints</strong>: <em>number</em>, <em>string</em> and <em>default</em> (when no hint is provided).</p><p><strong>If the target object (say </strong><strong>input) has a </strong><strong>[Symbol.toPrimitive] property defined on it, the following steps are taken:</strong></p><ol><li>Let result be the return value of input[Symbol.toPrimitive](<em>hint</em>).<br><em>This will throw a </em><strong><em>TypeError</em></strong><em> exception if </em><em>[Symbol.toPrimitive] is not a function. The </em><strong><em>hint</em></strong><em> argument can be one of </em><em>&quot;number&quot;, </em><em>&quot;string&quot; and </em><em>&quot;default&quot;.</em></li><li>If result is an object, throw a <strong>TypeError</strong> exception.</li><li>Return result.</li></ol><p><strong>Otherwise, the following happens:</strong></p><ol><li><strong>If the hint is </strong><em>string</em><strong>,</strong></li></ol><ul><li>Let result be the return value of input.toString().</li><li>If result is an object, update result with the return value of input.valueOf().</li><li>If result is an object, throw a <strong>TypeError</strong> exception.</li><li>Return result.</li></ul><p>2. <strong>Otherwise,</strong></p><ul><li>Let result be the return value of input.valueOf().</li><li>If result is an object, update result with the return value of input.toString().</li><li>If result is an object, throw a <strong>TypeError</strong> exception.</li><li>Return result.</li></ul><p>Now that we understand how the <strong>ToPrimitive</strong> abstract operation works, let’s see the resulting values for the salary object from before.</p><p><strong>For </strong><strong>String(salary) we have:</strong></p><pre><strong>String(salary) =&gt; ToString(ToPrimitive(salary, hint = string))</strong></pre><pre>// The <em>`salary`</em> object lacks a <em>[Symbol.toPrimitive]</em> method<br>// Also, hint is <em>string</em> — so start with <em>salary.toString()</em><br><strong>ToPrimitive(salary, hint = string) =&gt; salary.toString()</strong></pre><pre>// Since <em>salary.toString()</em> returns &quot;USD 150000&quot;,<br>// which is not an object<br><strong>ToPrimitive(salary, hint = string) =&gt; &quot;USD 150000&quot;</strong></pre><pre>// Therefore, we have:<br><strong>String(salary) =&gt; ToString(&quot;USD 150000&quot;)<br>String(salary) =&gt; &quot;USD 150000&quot;</strong></pre><p><strong>For </strong><strong>&quot;&quot; + salary we have:</strong></p><pre><strong>&quot;&quot; + salary =&gt; ToString(ToPrimitive(salary))</strong></pre><pre>// The <em>`salary`</em> object lacks a <em>[Symbol.toPrimitive]</em> method<br>// Also, hint is <em>not string</em> — so start with <em>salary.valueOf()</em><br><strong>ToPrimitive(salary) =&gt; salary.valueOf()</strong></pre><pre>// Since <em>salary.valueOf()</em> returns 150000,<br>// which is not an object<br><strong>ToPrimitive(salary) =&gt; 150000</strong></pre><pre>// Therefore, we have:<br><strong>&quot;&quot; + salary =&gt; ToString(150000)<br>&quot;&quot; + salary =&gt; &quot;150000&quot;</strong></pre><blockquote>You can learn more about the <a href="https://www.ecma-international.org/ecma-262/11.0/index.html#sec-toprimitive"><strong><em>ToPrimitive</em></strong></a> abstract operation from the <a href="https://www.ecma-international.org/ecma-262/11.0/index.html"><em>ECMAScript Language Specification</em></a>.</blockquote><h3>Minified JavaScript Code</h3><p>Most JavaScript code minification or compression tools attempt to replace certain values and tokens in the original code with more compact values or expressions in the minified code.</p><p>Here are some common examples:</p><pre>+----------------------+----------+<br>| Original             | Minified |<br>+----------------------+----------+<br>| true                 | !0       |<br>| false                | !1       |<br>| 1000                 | 1e3      |<br>| Infinity             | 1/0      |<br>+----------------------+----------+</pre><p>It’s very possible that due to some kind of configuration, some JavaScript code minification or compression tools might replace String(someValue) with &quot;&quot;+x, where x is the mangled variable name for someValue.</p><p>And if someValue is like the salary object we saw in the previous example, then it means the output from the minified code will differ from that of the original code.</p><h3>Type Casting Safely</h3><p>For safety, you might consider defining a [Symbol.toPrimitive] method on custom objects, especially those that define their own valueOf or toString methods.</p><p>For example, the createSalaryObject() function we saw earlier could be modified as follows to define a [Symbol.toPrimitive] method on the salary object that will be returned:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff3a1cc3382b8d55247ce5f39b8d9496/href">https://medium.com/media/ff3a1cc3382b8d55247ce5f39b8d9496/href</a></iframe><p>Defining a [Symbol.toPrimitive] method on custom objects might be an overkill. The code might rely on some third-party library that also defines custom objects. It might even be that the environment the code will run in does not support JavaScript symbols.</p><p>An alternative option will be to use String.call() to cast custom objects to strings instead of String(), since it is less likely that code minification tools will compress the former to a string concatenation expression.</p><pre>+-----------------------------------+----------------------+<br>| Original                          | Minified             |<br>+-----------------------------------+----------------------+<br>| String(someValue)                 | &quot;&quot;+x                 |<br>| String.call(null, someValue)      | String.call(null,x)  |<br>| String.call(someValue, someValue) | String.call(x,x)     |<br>+-----------------------------------+----------------------+</pre><p>Using String.call() severally in the original code might cause an increase in the size of the minified code. To prevent this, a custom helper function can be defined once and then used whenever a value needs to be explicitly cast to a string.</p><pre>function <strong>toStringHelper</strong>(value) {<br>  return <strong>String.call(value, value);</strong><br>}</pre><h3>Share &amp; Manage Reusable JS Components with <a href="https://bit.dev/">Bit</a></h3><p>Use <a href="https://bit.dev/"><strong>Bit</strong></a> (<a href="https://github.com/teambit/bit">Github</a>) to share, document, and manage reusable components from different projects. It’s a great way to increase code reuse, speed up development, and build apps that scale.</p><blockquote>Bit supports Node, TypeScript, React, Angular, Vue, and more.</blockquote><figure><a href="https://bit.dev"><img alt="" src="https://cdn-images-1.medium.com/max/800/0*P7OzkL0UqvExpTgi.gif" /></a><figcaption>Example: Exploring shared React components on <a href="https://bit.dev/">Bit.dev</a></figcaption></figure><figure><a href="https://bit.dev"><img alt="" src="https://cdn-images-1.medium.com/max/937/1*_q2wbLOtoJt5lbcGSWzPFw.gif" /></a><figcaption>Example: Exporting React components from a to-do app</figcaption></figure><p><a href="https://bit.dev">Bit. Composable software.</a></p><h3>Your Feedback</h3><p>Thanks for making out time to go through this post.</p><ul><li>Remember to <strong><em>drop your feedback or questions in the comments</em></strong>.</li><li>If you found this post insightful, go ahead, and <strong><em>hit the </em>Clap<em> button </em></strong>as much as you can to help others find it easily.</li><li>You can <strong><em>follow me on</em></strong> <strong><em>Twitter (@</em></strong><a href="https://twitter.com/gladchinda"><strong><em>gladchinda</em></strong></a><strong><em>)</em></strong> to get notifications about more insightful content coming up soon.</li></ul><p><strong><em>Happy coding…</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53e59ebee9f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/javascript-type-casting-gone-wrong-53e59ebee9f9">JavaScript Type Casting Gone Wrong</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Destructuring JavaScript Arrays Object(ively)]]></title>
            <link>https://codeburst.io/destructuring-javascript-arrays-objectively-df3df646e0ac?source=rss-ddcd0e9719e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/df3df646e0ac</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Glad Chinda]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 21:56:14 GMT</pubDate>
            <atom:updated>2020-08-03T21:56:14.992Z</atom:updated>
            <content:encoded><![CDATA[<h4>Overcome array destructuring limitations for array(like) objects.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lrZZuo_SNIoU3eWjfKRJA.jpeg" /></figure><h3>TL;DR</h3><p>Since JavaScript arrays are basically <em>objects</em> (with special behavior for index properties), they are valid targets for <strong><em>object destructuring</em></strong>. Hence, making the following destructuring statements equivalent.</p><pre><em>// Array to be destructured</em><br><strong>const RGB = [255, 180, 151];</strong></pre><pre><em>// Array Destructuring</em><br><strong>const [red, green, blue] = RGB;</strong></pre><pre><em>// Object Destructuring (equivalent)</em><br><strong>const {0: red, 1: green, 2: blue} = RGB;</strong></pre><p>Using the object destructuring syntax makes for more flexible and complex destructuring of arrays and array-like objects, where it wouldn&#39;t be possible or reasonable otherwise to use array destructuring, due to limitations.</p><blockquote><strong>Continue reading to find out more…</strong></blockquote><h3>Background</h3><p>The syntax for destructuring objects was added to the ECMAScript Language Specification starting from ES2015 (<em>popularly known as </em><strong>ES6</strong>). This syntax makes it possible to break down complex JavaScript values like objects into simpler parts that can be assigned to local variables.</p><p>The destructuring syntax comes in <strong><em>two basic flavors</em></strong>:</p><p><strong>1. Array destructuring</strong></p><pre><em>// Array that will be destructured</em><strong><br>const RGB = [255, 180];</strong></pre><pre><em>// Array Destructuring<br>// Skip the first item<br>// Set a default value (51) for the third item (`blue`)</em><br><strong>const [, green, blue = 51] = RGB;</strong></pre><pre><strong>console.log(green); </strong><em>// 180</em><strong><br>console.log(blue); </strong><em>// 51</em></pre><p><strong>2. Object destructuring</strong></p><pre><em>// Object that will be destructured</em><strong><br>const AUTHOR = {</strong><br>  <strong>name: &quot;Glad Chinda&quot;,<br>  lang: &quot;JavaScript&quot;</strong><br><strong>};</strong></pre><pre><em>// Object Destructuring<br>// Declare a local variable (`language`) for `lang`<br>// Set a default value (16) for `age`</em><br><strong>const {name, lang: language, age = 16} = AUTHOR;</strong></pre><pre><strong>console.log(name);</strong> <em>// &quot;Glad Chinda&quot;</em><strong><br>console.log(lang); </strong><em>// undefined</em><strong><br>console.log(language); </strong><em>// &quot;JavaScript&quot;</em><strong><br>console.log(age); </strong><em>// 16</em></pre><p>However, it is possible to have a destructuring syntax that is a mix of both flavors, nested in a certain way.</p><blockquote>In this post, we will focus on destructuring for arrays and other JavaScript iterables. If you are not already familiar with the destructuring syntax, you can check out <a href="https://codeburst.io/es6-destructuring-the-complete-guide-7f842d08b98f">ES6 Destructuring: The Complete Guide</a> to learn more.</blockquote><h3>Array Destructuring</h3><p>The <em>array destructuring</em> syntax proves useful for a number of applications. A very common application of array destructuring is in <strong><em>swapping variables</em></strong>.</p><p>Without the array destructuring syntax, swapping the values of two variables will always require a third <em>temporary</em> variable. With array destructuring, let’s just say that won’t be necessary.</p><pre><em>// Variables to be swapped</em><strong><br>let width = 1280;<br>let height = 720;</strong></pre><pre><em>// Swapping Variables (without array destructuring)<br>// A temporary variable is required</em><br><strong>let temp = width;</strong></pre><pre><strong>width = height;<br>height = temp;</strong></pre><pre><em>// Swapping Variables (with array destructuring)</em><br><strong>[width, height] = [height, width];</strong></pre><p>Another very common use of the array destructuring syntax is in combination with the <em>rest parameter</em> syntax for <strong><em>cloning arrays</em></strong>.</p><pre><em>// Array to be cloned</em><strong><br>const scores = [23, 27, 22, 41, 35];</strong></pre><pre><em>// Clone the `scores` array</em><br><strong>const [...scoresClone] = scores;</strong></pre><pre><strong>console.log(scoresClone);</strong> <em>// [23, 27, 22, 41, 35]</em><br><strong>console.log(scores === scoresClone);</strong> <em>// false</em></pre><p>Array destructuring isn’t limited to arrays alone (unlike the name implies), rather it can also be used with JavaScript <em>iterables</em> of all kinds such as strings, sets, <em>array-like</em> objects like <em>arguments </em>object, etc.</p><pre><em>// Destructuring a String</em><br><strong>const [firstChar, ...otherChars] = &quot;Hello&quot;;</strong></pre><pre><em>// Destructuring a Set</em><br><strong>const [,, thirdItem] = new Set([1, 2, 3, 4, 5]);</strong></pre><pre><strong>console.log(firstChar);</strong> <em>// &quot;H&quot;</em><br><strong>console.log(otherChars);</strong> <em>// [&quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;]</em><br><strong>console.log(thirdItem);</strong> <em>// 3</em></pre><h3>Limitations of Array Destructuring</h3><p>Let’s say we have an array <strong>ITEMS</strong> of <strong>100 items</strong> and we want to assign the value of the 3rd item in the array to a variable named <strong>thirdItem</strong>. Basically, that can be done as follows:</p><pre><em>// METHOD 1 — Using Item Index<br>// The 3rd item will be at index 2</em><br><strong>const thirdItem = ITEMS[2];</strong></pre><pre><em>// METHOD 2 — Using Array Destructuring<br>// Simply skip the first two items</em><br><strong>const [,, thirdItem] = ITEMS;</strong></pre><p>Now that was easy since we only needed the third item. What if we were interested in the last item instead? In that case, doing the assignment using the array destructuring syntax wouldn’t make any sense, because it literally means we have to skip the first 99 items(using <em>commas</em>) to get to the last item.</p><p>And that’s just for an array of 100 items. It’s even worse when the number of items in the array is not known at compile time. Getting the last item in the array will require knowing the length of the array — something like this:</p><pre><em>// Accessing the last item in the ITEMS array</em><br><strong>const lastItem = ITEMS[ITEMS.length — 1];</strong></pre><p>One might think for a moment here, that array destructuring can again be combined with the <em>rest parameter </em>syntax to solve this problem.</p><pre><em>//</em><strong><em> Throws a SyntaxError</em></strong><em><br>// Rest parameter element must always be the last element</em><br><strong>const [...skippedItems, lastItem] = ITEMS;</strong></pre><p>The combination of array destructuring and rest parameter, as shown above, fails with a <strong>SyntaxError</strong> due to the limitations placed on the rest parameter element:</p><ol><li>You can only have one rest parameter element.</li><li>The rest parameter element, whenever present, must be the last element.</li></ol><p><strong>Is there a different approach we can try?</strong><br>Since fundamentally, JavaScript arrays are <em>objects</em> (with special behaviors), one would guess that they should be valid targets for <strong><em>object destructuring</em></strong>.</p><h3>Object Destructuring to the Rescue</h3><p>According to the ECMAScript Language Specification, an <strong><em>array object</em></strong> is an exotic object that gives special treatment to array index property keys. What that means is that each index in the array is a valid property key of the array.</p><p>Hence, the following destructuring statements are equivalent (for an array):</p><pre><em>// Array to be destructured</em><br><strong>const RGB = [255, 180, 151];</strong></pre><pre><em>// Array Destructuring</em><br><strong>const [red, green, blue] = RGB;</strong></pre><pre><em>// Object Destructuring (equivalent)</em><br><strong>const {0: red, 1: green, 2: blue} = RGB;</strong></pre><p>Coming back to our problem from before with this new knowledge, we can get the last item in the <strong>ITEMS</strong> array and assign it to the <strong>lastItem</strong> variable like so:</p><pre><em>// Using object destructuring<br>// The last(100th) item will be at index 99</em><br><strong>const { 99: lastItem } = ITEMS;</strong></pre><p>Pushing further, let’s say we want to access items in sparse positions of the <strong>ITEMS</strong> array — for example the first, third, middle (50th), and last items. While it might be impractical to achieve that using the array destructuring syntax, it is a piece of cake when using the object destructuring syntax.</p><pre><em>// Using object destructuring<br>// ITEMS array contains 100 items</em><br><strong>const {<br>  0: firstItem,<br>  2: thirdItem,<br>  49: middleItem,<br>  99: lastItem<br>} = ITEMS;</strong></pre><p>It is also important at this point to note that the order of index properties does not matter when using object destructuring.</p><pre><em>// Using object destructuring<br>// Order of index properties does not matter</em><br><strong>const {<br>  2: thirdItem,<br>  99: lastItem,<br>  49: middleItem,<br>  0: firstItem<br>} = ITEMS;</strong></pre><h3>More with Object Destructuring</h3><p>When using object destructuring for arrays, we are not limited to only the index properties of the array object — we can also access other enumerable named properties existing on the array such as length.</p><pre><em>// Using object destructuring<br>// Get the first item and the length</em><br><strong>const { 0: firstItem, length } = ITEMS;</strong></pre><p>Using the object destructuring syntax, it becomes possible to access <em>computed properties</em>. For example, we can get the first, middle, and last items of the <strong>ITEMS</strong> array using computed properties as follows:</p><pre><em>// Using object destructuring<br>// Get the first, middle and last items</em><br><strong>const {<br>  </strong>0: firstItem<strong>,<br>  [ITEMS.length — 1]: lastItem</strong>,<strong><br>  [Math.floor(ITEMS.length / 2)]: middleItem<br>} = ITEMS;</strong></pre><p>We can modify the previous code snippet, introducing the length property of the array, like so:</p><pre><em>// Using object destructuring<br>// Get the length and first, middle and last items</em><br><strong>const {<br>  length,<br>  </strong>0: firstItem<strong>,<br>  [length — 1]: lastItem</strong>,<strong><br>  [Math.floor(length / 2)]: middleItem<br>} = ITEMS;</strong></pre><p>And if we choose to assign the value of the length property to a local variable with a different name, we can do this:</p><pre><em>// Using object destructuring<br>// Get the length and first, middle and last items<br>// The length is assigned to the `size` variable</em><br><strong>const {<br>  length: size,<br>  </strong>0: firstItem<strong>,<br>  [size — 1]: lastItem</strong>,<strong><br>  [Math.floor(size / 2)]: middleItem<br>} = ITEMS;</strong></pre><h3>Going Beyond Arrays</h3><p>The object destructuring syntax we’ve explored so far does not work for only JavaScript arrays. It can be used for strings and other kinds of <em>array-like</em> objects in JavaScript with special behavior for index properties — such as a function’s <em>arguments</em> object.</p><p><strong>Object destructuring for string:</strong></p><pre><em>// String to be destructured</em><strong><br>const STRING = &quot;Hello World!&quot;;</strong></pre><pre><em>// Object destructuring for string</em><strong><br>const {length, [length — 1]: lastChar} = STRING;</strong></pre><pre><strong>console.log(length);</strong> <em>// 12</em><br><strong>console.log(lastChar);</strong> <em>// &quot;!&quot;</em></pre><h3>📖 Further Reading</h3><p>For a more in-depth understanding of the destructuring syntax in JavaScript, the following resources will prove very useful.</p><ol><li><a href="https://codeburst.io/es6-destructuring-the-complete-guide-7f842d08b98f"><strong>ES6 Destructuring: The Complete Guide</strong></a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment"><strong>Destructuring assignment</strong></a></li><li><a href="https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/"><strong>ES6 In Depth: Destructuring</strong></a></li><li><a href="https://javascript.info/destructuring-assignment"><strong>Destructuring assignment</strong></a></li></ol><h3>Conclusion</h3><p>Using array destructuring has potential limitations when trying to destructure values in sparse positions of an array or <em>array-like</em> object. For example, it can be very daunting to get the last item in a large array using array destructuring.</p><p>However, switching to object destructuring provides more flexibility to handle even more complex destructuring on arrays and <em>array-like</em> objects. You are not just limited to index properties when using object destructuring—named and computed properties can be destructured as well if they are enumerable.</p><h3>Your Feedback</h3><p>Thanks for making out time to go through this post.</p><ul><li>Remember to <strong><em>drop your feedback or questions in the comments</em></strong>.</li><li>If you found this post insightful, go ahead, and <strong><em>hit the </em>Clap<em> button </em></strong>as much as you can to help others find it easily.</li><li>You can <strong><em>follow me on</em></strong> <strong><em>Twitter (@</em></strong><a href="https://twitter.com/gladchinda"><strong><em>gladchinda</em></strong></a><strong><em>)</em></strong> to get notifications about more insightful content coming up soon.</li></ul><p><strong><em>Happy coding…</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df3df646e0ac" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/destructuring-javascript-arrays-objectively-df3df646e0ac">Destructuring JavaScript Arrays Object(ively)</a> was originally published in <a href="https://codeburst.io">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Sync Your React App with the System Color Scheme]]></title>
            <link>https://medium.com/bitsrc/how-to-sync-your-react-app-with-the-system-color-scheme-78c0ad00074b?source=rss-ddcd0e9719e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/78c0ad00074b</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Glad Chinda]]></dc:creator>
            <pubDate>Wed, 20 May 2020 18:12:17 GMT</pubDate>
            <atom:updated>2020-05-20T18:12:17.001Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Dark Mode Implementation Guide for React</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*macm7IBXZOyqnMPWuFmBhg.jpeg" /></figure><p>Following the trend these last couple of years, you can agree that <a href="https://en.wikipedia.org/wiki/Light-on-dark_color_scheme">dark mode</a> design is gradually becoming a thing. Most of the popular applications, and even devices, have rolled out releases that feature a dark mode (<em>night mode</em>) color scheme.</p><p>Dark mode emphasizes the use of light-colored text and elements on a dark background — while maintaining good contrast. The reasoning behind this is somewhat straightforward — viewing the content in dark mode is not just easier on the eyes but also conserves device battery, as expressed by this Popular Science <a href="https://www.popsci.com/night-dark-mode-design">article</a>.</p><h3>TL;DR</h3><ul><li>Building apps with dark mode theming has become pretty common these days, hence it makes sense to understand some of the major ingredients needed to implement it — themes, switch, and context.</li><li>Simply letting the user toggle between light and dark modes via a simple switch can be counter-intuitive, especially when the user has a preferred color scheme already configured on the device or browser. Hence the need to detect and stay in sync with the user’s preferred color scheme on the device.</li><li>For React applications running on the web, CSS media queries alongside the window.matchMedia API can be leveraged for detecting and observing changes to the user’s preferred color scheme. React Native 0.62, on the other hand, ships with the Appearance API and the useColorScheme hook for the same purpose.</li><li>Depending on the app requirement, it is possible to use a combination that involves both inheriting the user’s preferred color scheme set on the device and allowing the user to manually override the app’s theme at any time, via some preferences.</li></ul><p>This post will not focus on building a design system or a UI library that enables theming. I recommend you learn it by looking at others&#39; design systems. You can use cloud component hubs like <a href="https://bit.dev"><strong>Bit.dev</strong></a> to explore components from different component libraries.</p><p>When you start building your own themeable UI components, make sure to publish them yourself to <a href="https://bit.dev">Bit.dev</a>. This way you’ll have your own “toolbox”, a collection of reusable and themeable UI components to use in your future apps.</p><figure><a href="https://bit.dev"><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Nj2EzGOskF51B5AKuR-szw.gif" /></a><figcaption>Example: exploring React components published on <a href="https://bit.dev">Bit.dev</a></figcaption></figure><h3>Dark Mode Implementation</h3><p>There are so many great dark mode implementations out there, and it has become very common these days to see web applications (such as blogs) include some kind of widget (like a switch) for toggling between viewing their content in either <em>light mode</em> or <em>dark mode</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hsxNw5-ICqu_TSFkhERNQg.gif" /><figcaption>A blog with <strong>Dark Mode</strong> toggle widget</figcaption></figure><p>Let’s examine a typical dark mode (color scheme) implementation for a React application. We will focus on three (3) major ingredients:</p><p>1. Themes<br>2. Switch<br>3. Context</p><h4>Themes</h4><p>Configure styles for both dark theme and light theme. Also, define mechanism for persisting current theme (e.g using local storage). Here is what the theme.js module looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11003421d174f574469abddeb78ab600/href">https://medium.com/media/11003421d174f574469abddeb78ab600/href</a></iframe><h4>Switch</h4><p>Define the mechanism for switching between both themes. The mechanism should be available to the user via a dark mode toggle switch that can be interacted with. Here is what the DarkModeToggleSwitch component looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/229bbab109c74d0a8d57bc55cbd27488/href">https://medium.com/media/229bbab109c74d0a8d57bc55cbd27488/href</a></iframe><h4>Context</h4><p>Switching between themes should also change the app-level theme context, thereby causing the app to re-render with the appropriate styles. Here is the main App.js component that handles the context switching logic and passes it down the whole app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95c45096ccd289f083ca20e84e5f22b4/href">https://medium.com/media/95c45096ccd289f083ca20e84e5f22b4/href</a></iframe><h3>Device Consideration</h3><p>Most devices these days (smartphones, tablets, laptops, etc) provide a setting for enabling the dark mode color scheme at a system-wide level. Some even provide additional options for scheduling when to enable dark mode — usually dependent on the time of the day.</p><p>Also, we now have browsers providing browser-level color scheme settings either as a built-in feature, via a browser extension, or via some preference simulator. Usually, the browser-level color scheme tends to override the system-wide color scheme setting on the device.</p><p>While it can be quite useful to allow the user to quickly toggle between light mode and dark mode with a simple switch at the app-level, it might be counter-intuitive sometimes, especially when the user already has a system-wide color scheme set on the device or at the browser-level.</p><p>Hence, being able to know the preferred color scheme of the user’s device or browser becomes very important. Thankfully, CSS media queries together with the window.matchMedia Web API has got us covered.</p><h4>Color Scheme Detection</h4><p>The CSS <a href="https://drafts.csswg.org/mediaqueries-5/#prefers-color-scheme">Media Queries Level 5 specification</a> adds the prefers-color-scheme feature that reflects the user’s desire to view the page’s content in a light or dark color theme. The possible values for this feature as defined in that specification are as follows:</p><ul><li>dark — User prefers a dark color theme</li><li>light — User prefers a light color theme</li><li>no-preference — User hasn’t indicated any preference</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U15h8PcybCcCqd8AoxA4og.png" /><figcaption>CSS <strong>prefers-color-scheme</strong> media feature</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0820ddac30b76644e4feed57ae215fb6/href">https://medium.com/media/0820ddac30b76644e4feed57ae215fb6/href</a></iframe><p>Detecting the user’s preferred color scheme and modifying the styles appropriately is pretty straightforward using CSS. However, that isn’t so helpful to us when building React apps that are aware of the user’s preferred color scheme. For that, we will need the means to detect the color scheme from JavaScript code — that’s what window.matchMedia is for.</p><h4>Staying in Sync</h4><p>While detecting the user’s current preferred color scheme is an important first step, staying in sync with changes to the user’s color scheme preference is as important — to ensure the app responds or re-renders accordingly to reflect the changes.</p><p>One way to go about this is to set up a media query change listener. When window.matchMedia is called, it returns a <a href="https://drafts.csswg.org/cssom-view/#the-mediaquerylist-interface">MediaQueryList</a> object. We have already seen the matches property of this object — which returns a boolean value that indicates whether the media query matches.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57e2e6eedfa7de85332be947aedcb172/href">https://medium.com/media/57e2e6eedfa7de85332be947aedcb172/href</a></iframe><p>However, we can also register a change event listener on the MediaQueryList object to detect when the media query no longer matches.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60ebdcfc629b2ca82f03f30cdc7ce554/href">https://medium.com/media/60ebdcfc629b2ca82f03f30cdc7ce554/href</a></iframe><p>Now that we have a pretty solid idea of how to detect and stay in sync with the user’s preferred color scheme, we can proceed with refactoring our initial React application — to make it aware of the user’s device color scheme.</p><h3>Hooking up React</h3><p>Currently, switching the theme of our React app requires user interaction (click interaction) with the dark mode toggle switch. However, we want to refactor the application to inherit the user’s preferred (system-wide) color scheme as it has been set on the device.</p><p>Wait a minute, that will mean we no longer need the dark mode toggle switch. The app should be able to detect and stay in sync with the system-wide color scheme. To achieve this, we will aggregate all the techniques we’ve just seen about color scheme detection into a custom React hook — which we will call useColorScheme.</p><h4>The useColorScheme Hook</h4><p>Before we dive into defining the useColorScheme custom React hook, let’s create the module with a couple of helper functions as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a658ed7f71e842ec2b950a07a8d9df0/href">https://medium.com/media/3a658ed7f71e842ec2b950a07a8d9df0/href</a></iframe><p>Here, we have defined two helper functions:</p><ul><li><strong>resolveTargetColorScheme</strong> — Accepts a target color scheme as its argument and returns either &#39;dark&#39; or &#39;light&#39;. Notice that if the specified target color scheme is &#39;no-preference&#39; or cannot be parsed into any of the schemes in the COLOR_SCHEMES list, then the DEFAULT_TARGET_COLOR_SCHEME value is returned instead.</li><li><strong>getCurrentColorScheme</strong> — This returns an object with its query property set to a MediaQueryList object that matches the current user preferred color scheme, and its scheme property set to the name of the current color scheme as it appears on the COLOR_SCHEMES list. Notice that the function caches the MediaQueryList objects to avoid re-creating them each time.</li></ul><p>Now, here comes the useColorScheme hook function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad6781911b10dec7205aaf8b502be4ec/href">https://medium.com/media/ad6781911b10dec7205aaf8b502be4ec/href</a></iframe><p>Quite a number of interesting things are going on inside this useColorScheme hook. Let’s quickly run through them from top to bottom.</p><ul><li>Using the useRef() hook, create two mutable ref objects: isMounted (holds a boolean value indicating that the component is still mounted) and colorScheme (holds the current color scheme object returned from a call to the getCurrentColorScheme function).</li><li>Resolve targetScheme by calling the resolveTargetColorScheme function with what was passed to the hook as the target color scheme. Notice the use of the useMemo() hook to ensure that the value is not recomputed except the hook is called with a different target color scheme value.</li><li>The initial scheme state function calls the getCurrentColorScheme function and initializes the colorScheme ref object with the returned object. It then sets the initial scheme state to the value of the returned object’s scheme property.</li><li>The useEffect() hook is used to initialize the isMounted ref object to true when the component is mounted and also to set up a change listener on the MediaQueryList object of the current colorScheme ref object. The cleanup function sets isMounted to false and removes the previously set change listener. Notice that the useEffect() side-effect will be called only once since the dependencies list is an empty array ([]).</li><li>The schemeChangeHandler function runs when the user’s color scheme has changed. When executed, it removes the change listener from the current MediaQueryList object, updates the colorScheme ref with the new object returned from getCurrentColorScheme, updates the scheme state if the component is still mounted, and finally sets up a change listener on the new MediaQueryList object of the current colorScheme ref object.</li><li>Finally, the hook returns a boolean — true if the current scheme state matches the color scheme resolved as targetScheme, and false otherwise.</li></ul><p>That was a mouthful. With the useColorScheme hook in place, all that remains now is to modify the App component from before to use the hook.</p><h4>Modify the App Component</h4><p>After making a couple of modifications to the App component, we should be good to go. Here is what the updated App.js module is expected to look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/666709bab8406ad2f22ddc9c55cd27b8/href">https://medium.com/media/666709bab8406ad2f22ddc9c55cd27b8/href</a></iframe><p>Notice that we are no longer rendering the dark mode toggle switch. Also, there is no longer a toggle function for switching between color schemes. Switching between color schemes is now as easy as changing the color scheme preference on either the device or the browser (if available), and then the app updates accordingly.</p><h4>An aside on React Native</h4><p>Before we move ahead, let’s briefly consider how we can apply the above concept to React Native apps. Interestingly, react-native from version 0.62 now ships with the Appearance API and the useColorScheme hook — which is very useful for detecting and staying in sync with the user-preferred color scheme.</p><ul><li><strong>Detecting the current user preferred color scheme will require using the </strong><strong>getColorScheme method of the </strong><strong>Appearance API as follows:</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29bd064ff4ed286f3184e8d56f4c0dae/href">https://medium.com/media/29bd064ff4ed286f3184e8d56f4c0dae/href</a></iframe><ul><li><strong>Staying in sync with changes to the user preferred color scheme will require using the </strong><strong>useColorScheme hook as follows:</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e4fad36981ef92055bc972eb873934b/href">https://medium.com/media/8e4fad36981ef92055bc972eb873934b/href</a></iframe><p>If you are using a version of react-native that was released prior to version 0.62, the <a href="https://www.npmjs.com/package/react-native-appearance">react-native-appearance</a> package can be used as an alternative.</p><h3>Best of Both Worlds</h3><p>With the new modifications, our React app is now able to change its theme to reflect the user’s preferred color scheme at the device or browser level. However, it has completely lost the ability for the user to manually override the app theme at any time. Now the question is: <strong><em>“Why have either when we can have both?”</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzPMoPOkNdVuRtw_qckUWw.gif" /><figcaption><strong>Dark Mode toggle widget</strong> (with system color switch)</figcaption></figure><p>For that to happen, we will need to refactor our React application to support both behaviors. This will require that we maintain an additional setting on the app to enable the user to decide if he wants to inherit the system-wide color scheme or manually override it.</p><p>First, let’s begin the refactoring with the theme.js file from before. Here is what the updated module will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fbf4f35b4ea82338efc2f318070130f/href">https://medium.com/media/2fbf4f35b4ea82338efc2f318070130f/href</a></iframe><p>Here, we are exporting a new InheritSystem object for getting and updating the theme.inherit_system setting value. Notice how the __themeSettingFactory__ function was used as a convenience function for creating the settings objects.</p><p>Next, we will extract all color scheme logic from the App component into a custom React hook — which we will call useTheme. Here is what the hook looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc7eb4c2413400582fbc1af825493573/href">https://medium.com/media/dc7eb4c2413400582fbc1af825493573/href</a></iframe><p>In the useTheme hook, we are bringing in everything we have done so far into one place. Notice how we determine the theme by first checking the inheritSystem state to determine if we should use the dark state from the user’s device or the user’s manually set darkMode state.</p><p>Also, we defined a __stateToggleFactory__ higher-order helper function for creating toggle functions for the two states: darkMode and inheritSystem.</p><p>The useTheme custom hook returns an object with theme, darkMode and inheritSystem properties. Both the darkMode and inheritSystem properties are objects themselves with two properties: on — which is the boolean value of the state, and toggle — which is the toggle function for the state.</p><p>Finally, we will go ahead and refactor the App component from before to use the useTheme hook we just created. The final App.js file should now look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a74bd6a4d107f6c42ff1e55770b1e3bf/href">https://medium.com/media/a74bd6a4d107f6c42ff1e55770b1e3bf/href</a></iframe><p>Notice that the App component now looks cleaner and less bloated. Also, we have removed the rendering logic for the color scheme controls — they can be rendered in any way as required for the application.</p><h3>Final Note</h3><p>At last, the article comes to a close. In the course of this article, we’ve been able to consider how we can factor in the user preferred system-wide color scheme into our React apps. We’ve also been able to consider how we can bring color scheme manual override functionality into the mix.</p><p>While localStorage was used throughout this article for persisting preference values, you are not in any way limited to using it. Based on your app requirements, it is possible to get and update preference values via the traditional HTTP Cookies, an API Service, or any other form of storage mechanism available to you.</p><p>Rendering logic has been skipped throughout the article to keep the code snippets as concise as possible. In a real app, you are free to handle rendering as you deem fit or based on your app requirements. Also, you are at liberty to manage theming with whatever package works for you — for example, using <a href="https://styled-components.com/">styled-components</a> <a href="https://styled-components.com/docs/advanced#theming">theming</a>.</p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/theming-react-components-with-css-variables-ee52d1bb3d90">Theming React Components with CSS Variables</a></li><li><a href="https://blog.bitsrc.io/how-to-build-a-modular-react-ui-library-with-bit-and-bit-dev-7b7cf49b5146">Create a Modular React Component Library</a></li><li><a href="https://blog.bitsrc.io/localstorage-sessionstorage-the-web-storage-of-the-web-6b7ca51c8b2a">How to Use the Web Storage API</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78c0ad00074b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/how-to-sync-your-react-app-with-the-system-color-scheme-78c0ad00074b">How to Sync Your React App with the System Color Scheme</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking Custom Checkboxes And Radios]]></title>
            <link>https://medium.com/hackernoon/hacking-custom-checkboxes-and-radios-5d48230440d?source=rss-ddcd0e9719e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d48230440d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[hackernoon-top-story]]></category>
            <dc:creator><![CDATA[Glad Chinda]]></dc:creator>
            <pubDate>Fri, 15 Mar 2019 09:16:00 GMT</pubDate>
            <atom:updated>2019-05-02T11:25:13.669Z</atom:updated>
            <content:encoded><![CDATA[<h4>Cosmetic improvements to checkboxes and radios using CSS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTzsWgsSGnHrA5Vocmlr1A.jpeg" /></figure><p>Radios (or <em>radio buttons</em>) and checkboxes are very important input elements commonly found in so many forms on the web.</p><p><strong>Checkboxes</strong> are used where multiple values from a list of predefined values may apply — for example, marking multiple files for deletion from a list of files.</p><p><strong>Radio buttons</strong> on the other hand are used where only one value is applicable — for example, selecting gender from a list.</p><p>In this tutorial, we’ll examine using a step-by-step approach, how to <strong>improve the aesthetics and appearance</strong> of radios and checkboxes using CSS <strong>while still preserving the accessibility</strong> of the input elements.</p><p><em>In order to fully appreciate this tutorial, a basic understanding of CSS — selectors and style rules is required. However, you don’t really have to be a CSS expert to follow through.</em></p><h3>Motivation</h3><p>When it comes to appearances, radios and checkboxes are somewhat awkward and inconsistent across different browsers. Often times, a uniform appearance is desired for checkboxes and radio buttons, irrespective of the browser being used.</p><p>Most <a href="https://hackernoon.com/tagged/css">CSS</a> frameworks like Bootstrap already provide custom styling for the appearance of these input elements. However, if you are not using a CSS framework, you may need to be able to customize your own checkboxes and radio buttons — hence this tutorial.</p><h3>Design Blueprint</h3><p><strong>Here is an outline of steps to follow</strong> in order to create a customized radio button or checkbox. In this list, I will keep referring to a <em>checkbox</em> or <em>radio button</em> as just <strong><em>input element</em></strong>.</p><ul><li><strong>Ensure you have a label for the input element</strong>.<br>Wrap the input element with a &lt;label&gt;&lt;/label&gt; element and attach a label text for the input element if necessary. This is also useful for maintaining the accessibility of the input element.</li><li><strong>Add the customization element after the input element.<br></strong>The customization element is an empty element that will hold all the styles for the custom appearance of the input. It must come after the input element and they must both have the same parent element.</li><li><strong>Make the native input element go away.<br></strong>Add the necessary styles to prevent the native input element from being visually presented. Avoid using styles that will remove the input element from the visual flow of the page, since they will be ignored by screen readers and will also impact keyboard accessibility negatively.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d6a52d13bf53999125ac0420cb0f7fc/href">https://medium.com/media/4d6a52d13bf53999125ac0420cb0f7fc/href</a></iframe><ul><li><strong>Customize all you want.<br></strong>Add the necessary styles to the customization element to get the desired custom appearance of the input. Use the :checked pseudo-class to add styles based on the checked state of the input element.CSS generated content may be used if necessary, leveraging on ::before and ::after pseudo-elements.</li></ul><h3>Implementation</h3><p>We will go ahead and implement our customizations based on the <a href="https://hackernoon.com/tagged/design">design</a> blueprints we’ve just seen. We’ll start with a minimalistic markup for the custom input element and then the styles.</p><h4><strong>Basic Markup</strong></h4><p>Here is a sample markup HTML for the input element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c653d982e58e4e5b98776d84858c2065/href">https://medium.com/media/c653d982e58e4e5b98776d84858c2065/href</a></iframe><p>The checkbox element here is defined with a check-custom class. The customization element for the checkbox is given a class of check-toggle.</p><p>Using classes in this way makes it easy to opt in or out of the customization. For example — if the check-custom class is not passed, the native checkbox is shown instead.</p><h4>Hide the Native Element</h4><p>You could easily attach the hidden attribute to the input element to prevent it from being visually presented like so:</p><pre>&lt;input type=&quot;checkbox&quot; class=&quot;check-custom&quot; <strong>hidden</strong>&gt;</pre><p>However, this should be discouraged. CSS styles should be used to hide the native input element instead.</p><p>Here is a simple style definition to ensure that the native input element is not visually presented.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52bb032a209b6a1fb393f5a2345fdf03/href">https://medium.com/media/52bb032a209b6a1fb393f5a2345fdf03/href</a></iframe><p>Here, an attribute selector and a .check-custom class selector are used with the input type selector to ensure that the styles apply to only checkboxes with the specified class.</p><h4>Customize the Checkbox</h4><p>First, we will add the basic styles for the appearance of the checkbox as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41068c5ab37b5334fa42f37c19a6cc09/href">https://medium.com/media/41068c5ab37b5334fa42f37c19a6cc09/href</a></iframe><p>Notice how the <em>general sibling combinator</em> (<strong>A ~ B</strong>) was used in the selector to target the customization element after the input element. Here it is again:</p><pre>input[type=&#39;checkbox&#39;].check-custom <strong>~</strong> .check-toggle</pre><p>This selector will match any element with a check-toggle class, that is a direct sibling of and comes after any checkbox input element with a check-custom class.</p><p>Finally, it’s time to add styles for the various states of the check box.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14dc5929dd5a46c5a7d107f3a4f3efd6/href">https://medium.com/media/14dc5929dd5a46c5a7d107f3a4f3efd6/href</a></iframe><p>Notice here that I have used an inline SVG of a white checkmark in addition to a blue derivative color as the background for the custom checkbox when it is checked.</p><p>Though I have used very simple styles here, it is completely up to you to use as much styling as will be required for the customization you desire.</p><p>Here are the complete styles for the custom checkbox:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf297458a62fc982f54bf3355dbf1491/href">https://medium.com/media/bf297458a62fc982f54bf3355dbf1491/href</a></iframe><h4><strong>Comparison Demo</strong></h4><p>Here is a very simple demo, comparing the appearances of the custom and native checkboxes. (A<em>dditional styles have been applied to aid the visual presentation</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*hRJzg0dt5iAM-A5i.gif" /></figure><h3>Implementing Custom Radio Button</h3><p>We’ve already seen an implementation for a custom checkbox. Let’s quickly see how we can implement a custom radio button by following the design blueprint we saw earlier.</p><h4>Basic Markup</h4><p>Here is a sample markup HTML for the radio button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7973f40c084228fb0ca5d299218ecb22/href">https://medium.com/media/7973f40c084228fb0ca5d299218ecb22/href</a></iframe><p>Here, we have changed the input type to radio. We have also retained the class names on the elements for consistency.</p><p>Before we go on to writing the styles for our custom radio button, let’s have a fair idea of what our radio button should look like.</p><p>Here is a side-by-side comparison between the appearance of our custom radio button and the native one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*ms_RKDTldJhRV_Of.gif" /></figure><h4>Styling the Radio Button</h4><p>From the screenshot above, it can be seen that our custom radio button has something that looks like a small box at its middle when it is in checked state.</p><p>To create that box for the checked state, we will leverage on the ::after pseudo-element of the customization element.</p><p>All other styles are almost the same with what we saw before for the checkbox. Here are the styles needed to create our custom radio button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/127c8fcbd1d61cdfbeeb2656e4802f45/href">https://medium.com/media/127c8fcbd1d61cdfbeeb2656e4802f45/href</a></iframe><p>Notice here that we are now using the input[type=’radio’] base selector to ensure that we are targeting only radio buttons. Remember again that it’s completely up to you to style the custom radio button however you seem fit.</p><h3>Case Study: Toggle Switch</h3><p>There are a couple of use cases for customized checkboxes and radio buttons that may not be so apparent. One of these is the <strong>toggle switch</strong>.</p><p>A <strong>toggle switch</strong> can be seen as a checkbox that toggles between two values based on its checked and unchecked state — usually having the appearance of a switch.</p><p>We can modify the styles for the customization element of our custom checkbox to give it the appearance of a switch.</p><h4>The Markup</h4><p>Let’s start with a sleight modification of the markup to add a toggle-switch class to the input element. Here is what it is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2493725f8f9527d5963d3dedba76591/href">https://medium.com/media/d2493725f8f9527d5963d3dedba76591/href</a></iframe><h4>Checkbox — Why not Radio?</h4><p>Notice, in the markup for the toggle switch, that we are using an input type of checkbox for the toggle switch. A good question will be — <strong>“Can we also use a </strong><strong>radio input element?”</strong></p><p><strong>The answer is NO.</strong> The reason is due to the difference in the toggle behavior of a radio button and a checkbox when they are already in checked state.</p><p>A radio button on its own cannot be unchecked by mere user interaction when already in checked state. Hence, it is not ideal for use as a toggle switch.</p><p>This simple demo shows the difference between using a radio button and a checkbox as the basis for a toggle switch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*SMn0MD8_AjZMAxEs.gif" /></figure><h4>The Styles</h4><p>We will make a couple of modifications to the styles for the customization element to make it look like a switch.</p><p>A typical switch consists of an <strong>outer frame</strong> and an <strong>inner slider</strong> that aligns to either the left or right side of the frame depending on the state of the switch.</p><p>To achieve this design, we will leverage on the ::before and ::after pseudo-elements of the customization element. The ::before pseudo-element will be the outer frame, while the ::after pseudo-element will be the inner slider.</p><p>The resulting toggle switch will look like the following screenshot — <em>(Additional styles have been applied to aid the visual presentation)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*XO2ph3d1IC9uUhY7.gif" /></figure><p>Here are the styles for the toggle switch:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d1e3d98a9e9b6e9dc8ac73cf4d500ed/href">https://medium.com/media/9d1e3d98a9e9b6e9dc8ac73cf4d500ed/href</a></iframe><h3>About Accessibility</h3><p>For all the customizations we did in this tutorial, we were able to ensure that our custom radio buttons and checkboxes remained accessible — which is a very good feat by the way.</p><p>Hence, tab focusing, check toggling with spacebar and all other accessibility characteristics of the input elements are preserved. This is possible because:</p><ul><li>the &lt;label&gt;&lt;/label&gt; element was used to wrap the input elements. Hence always remember to wrap the native input element and the customization element in a parent &lt;label&gt; element.</li><li>the native input elements are still preserved in the visual flow of the page, even though they are not visually presented.</li></ul><p>Another important improvement on the accessibility of our customized elements will be to add a text or element that provides a readable label — using any of the following options:</p><ul><li>a child element or text within the parent &lt;label&gt; element.</li><li>a hidden label text specified using the aria-label attribute.</li><li>a separate element linked to the input element using the aria-labelledby attribute.</li></ul><p>Still on ARIA attributes, you can also use the aria-checked attribute together with the basic checked to indicate checked state of the input elements.</p><p>For the toggle switch, you should add the ARIA role role=”switch” to the input element to indicate that it is a toggle switch.</p><p>Finally, always ensure that you employ adequate styles for the focus state of the input element in order to provide a useful visual cue.</p><h3>Conclusion</h3><p>Finally, we’ve come to the end of this tutorial and we’ve seen a very simple design blueprint that can guide us in making cosmetic changes to native radio buttons and checkboxes with just CSS, and still preserving their accessibility.</p><p>Like stated in the tutorial, you are not restricted to the customization styles used in the tutorial. In fact, it’s completely up to you to style the custom elements however you seem fit.</p><p><strong>Clap &amp; Follow</strong></p><p>If you found this article insightful, feel free to give some rounds of applause if you don’t mind.</p><p>You should follow me on <strong>Medium</strong> (<a href="https://medium.com/u/ddcd0e9719e5">Glad Chinda</a>) for updates on more insightful articles like this one. You can also follow me on my <strong>Twitter</strong> handle (<a href="https://twitter.com/@gladchinda">@gladchinda</a>).</p><p><strong><em>Enjoy coding…</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d48230440d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/hacking-custom-checkboxes-and-radios-5d48230440d">Hacking Custom Checkboxes And Radios</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conditional JavaScript for Experts]]></title>
            <link>https://medium.com/hackernoon/conditional-javascript-for-experts-d2aa456ef67c?source=rss-ddcd0e9719e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2aa456ef67c</guid>
            <category><![CDATA[javascript-for-experts]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Glad Chinda]]></dc:creator>
            <pubDate>Thu, 18 Oct 2018 11:01:08 GMT</pubDate>
            <atom:updated>2019-05-02T11:25:14.569Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mastery of conditional expressions for shorter codes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uru6V6HxRDJlMBLAWrfltQ.jpeg" /></figure><p>Conditionals are a very important aspect of the syntax of every programming language. If you have been <a href="https://hackernoon.com/tagged/programming">programming</a> for sometime in any of the popular languages, you should already be familiar with the if..elif..else or switch conditional statements. They are very useful for making decisions in programs.</p><p>For example, let’s say a treasure chest has been designed such that only Glad (<em>that’s me</em>) should be able to open it. This logic can be programmatically represented (in Python) as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc51a5619b654fb9e7af09df9c0691a7/href">https://medium.com/media/cc51a5619b654fb9e7af09df9c0691a7/href</a></iframe><p>Although, the previous code snippet was written in Python syntax, this article is strictly for <a href="https://hackernoon.com/tagged/javascript">JavaScript</a>. However, most of the techniques shown here may be applied to a couple other programming languages.</p><p><em>I promise from this moment that you will not find any other line of code in this article written in the syntax of any other programming language besides JavaScript.</em></p><p>In this article, more emphases will be laid on conditional expressions (using logical operators) in JavaScript and how they can be used to make codes shorter, than on conditional statements.</p><h3>Expressions vs Statements</h3><p>Before proceeding, you need to be able to distinguish between expressions and statements in JavaScript. Here is a very simple analogy:</p><blockquote><em>Expressions are to JavaScript what phrases are to grammar, while statements are to JavaScript what sentences are to grammar.</em></blockquote><p><strong>An <em>expression </em>is any phrase that the JavaScript engine can evaluate to produce a value.</strong></p><p><strong>For example:</strong> literals, assignments, function expressions, logical, bitwise or arithmetic operations, object property access, function invocations, eval, etc.</p><p>The following code snippet show some JavaScript expressions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de8cb4b12b8caaee31ad696645fdc04c/href">https://medium.com/media/de8cb4b12b8caaee31ad696645fdc04c/href</a></iframe><p><strong>A <em>statement </em>is any sentence or command that the JavaScript engine can execute to make something happen or cause some side-effect.</strong></p><p><strong>For example:</strong> conditionals, variable or function declarations, loops, throw, return, try/catch/finally, etc.</p><p>Some JavaScript expressions like <em>assignments</em> and <em>function invocations</em> may have side-effects, and as a result can usually be used as statements (<strong><em>expression statements</em></strong>).</p><h3>Conditions and Booleans</h3><p>A critical requirement of every conditional is the <strong>condition</strong>. The condition is what determines the decision to be made in the program.</p><p>In JavaScript, this condition can be any valid expression. Usually, this condition expression, however complex it is, is evaluated to one of two values called <strong>booleans</strong>: either true or false.</p><p>A proper understanding of how the JavaScript engine converts these condition expressions to booleans is necessary for writing correct and predictable conditional logic.</p><p>Here are two fundamental concepts that can enable us to understand the conversions:</p><ul><li>Identifying <em>truthy</em> and <em>falsy</em> values</li><li>Understanding <em>short-circuiting</em> in logical operations</li></ul><h4>Truthy vs Falsy</h4><p>Every value in JavaScript can be classified as either <em>truthy</em> or <em>falsy</em>. The <em>falsy</em> values in JavaScript are as follows:</p><ul><li>&#39;&#39; or &quot;&quot; or ``(<em>an empty string</em>)</li><li>0 or -0 (<em>the number 0</em>)</li><li>null</li><li>undefined</li><li>NaN</li><li>false</li></ul><p>Every other value besides the ones in this list are <em>truthy</em> values. Whenever JavaScript expects a boolean value, <em>truthy</em> values are implicitly coerced to true while <em>falsy</em> values are implicitly coerced to false.</p><p>However, if you want to be deliberate or explicit about the type coercion, you can use the native Boolean function to convert any value its corresponding boolean.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83c9e3dbf1333b6c6468866bfe3e29d7/href">https://medium.com/media/83c9e3dbf1333b6c6468866bfe3e29d7/href</a></iframe><p>You can also use the logical <strong>NOT</strong> (!) operator to convert a value to a boolean. The ! operator converts it’s operand to the inverse boolean value, hence, it always evaluates to a boolean value.</p><p>Using the ! operator evaluates to false on truthy values and true on falsy values. To convert a value to its corresponding boolean, you need to use the ! operator twice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/793021926d2722814f7ebcd35879f2f8/href">https://medium.com/media/793021926d2722814f7ebcd35879f2f8/href</a></iframe><h4>Short-Circuiting</h4><p>The <strong>AND</strong> (&amp;&amp;) and <strong>OR</strong> (||) logical operators both require two operands, and are used to perform Boolean operations on their operands.</p><p>Given that the two operands are booleans (true or false),</p><ul><li>&amp;&amp; operation returns true only when both operands are true, otherwise it returns false.</li><li>|| operation returns false only when both operands are false, otherwise it returns true.</li></ul><p>Note that the &amp;&amp; operator has a higher precedence than the || operator, and as such, is usually evaluated first. Hence, when they are used together in an expression, you may use parentheses (()) for grouping in order to alter the evaluation order. Consider the following code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bc70784460f7a9cd4a4b94d83f0e070/href">https://medium.com/media/2bc70784460f7a9cd4a4b94d83f0e070/href</a></iframe><p>When using these operators, the first operand is always evaluated. However, the second operand may never be evaluated depending on the result from evaluating the first operand. This behavior is known as <strong><em>short-circuiting</em></strong>.</p><p>The &amp;&amp; and || operations do not always produce a boolean value. Generally, they can produce just any value. Here is a more concise description of their behavior based on <em>short-circuiting</em>:</p><ul><li>&amp;&amp; operator first evaluates its first operand. If the resulting value is <em>truthy</em>, it evaluates the second operand and returns its value. However, if the value of the first operand is <em>falsy</em>, the second operand is never evaluated, it just returns the <em>falsy</em> value from the first operand.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b75ba405f4ef72cb73a8544c68c1b14/href">https://medium.com/media/3b75ba405f4ef72cb73a8544c68c1b14/href</a></iframe><ul><li>|| operator first evaluates its first operand. If the resulting value is <em>truthy</em>, the second operand is never evaluated, it just returns the <em>truthy</em> value from the first operand. However, if the value of the first operand is <em>falsy</em>, it evaluates the second operand and returns its value.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a8fe0f8b38288a0bbdc0a3a80f74c58/href">https://medium.com/media/6a8fe0f8b38288a0bbdc0a3a80f74c58/href</a></iframe><h3>Replacing Statements with Expressions</h3><p>You now have a clear understanding of the <em>short-circuiting</em> concept and how condition expressions get converted to booleans.</p><p>Next, you will see how some conditional statements can be converted to simple expressions. You will also see how such conversions can make your code look more compact and shorter.</p><h4>1. Simple If Statements</h4><p>Very simple if statements can easily be replaced with conditional expressions by leveraging on the concept of <em>short-circuiting</em>. Consider the following code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e9629e6ad3ee16ffb8ddfd928d2cee0/href">https://medium.com/media/7e9629e6ad3ee16ffb8ddfd928d2cee0/href</a></iframe><p>In this code snippet, the if statement ensures that the deletePost()function is only invoked when the condition evaluates to true.</p><p>This simple if statement can be replaced with a very simple conditional expression as shown in the following code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8850bd761f2d287c8d19cb1e3df47afa/href">https://medium.com/media/8850bd761f2d287c8d19cb1e3df47afa/href</a></iframe><p>Though this conditional expression works in a similar fashion as the previous if statement, they are actually different.</p><p><em>The conditional expression produces a value, which means it can be assigned to a variable, or used any other place where a value is required.</em></p><p>Remember that using conditional expressions like this means you have to be very careful about short-circuiting caveats. It is very possible that an operand may not be evaluated as we saw in the previous section on short-circuiting.</p><h4>2. If…Else Statements</h4><p>Consider the following dummy code snippet for determining the strength of a password:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20d2bc550051ad3670e053b8ee1dacfb/href">https://medium.com/media/20d2bc550051ad3670e053b8ee1dacfb/href</a></iframe><p>The intent of this code snippet is very simple — check if the password is more than 7 characters long. If it is, then set the strength variable to “Strong”, otherwise set it to “Weak”.</p><p>The previous code snippet can be shortened to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1e4f57395ab6e51de028c9d1e27437e/href">https://medium.com/media/d1e4f57395ab6e51de028c9d1e27437e/href</a></iframe><p>This code snippet does exactly what the previous one does, all in just one line. This looks pretty good already. The following code snippet tries to review the evaluation of the conditional expression.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fd579b855a17e80af1f46dff31f8c5b/href">https://medium.com/media/2fd579b855a17e80af1f46dff31f8c5b/href</a></iframe><p>There is a better way of writing these kinds of if...else conditional expressions — using the <strong><em>conditional operator</em></strong> also called the <strong><em>ternary operator</em></strong>. Its syntax looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b94c0b68c3b95d5a8ba8c46df408595/href">https://medium.com/media/3b94c0b68c3b95d5a8ba8c46df408595/href</a></iframe><p>The previous code snippet can hence be rewritten using the ternary operator as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14cf4db434a9c1e7afda96db1bddfee0/href">https://medium.com/media/14cf4db434a9c1e7afda96db1bddfee0/href</a></iframe><p><em>Although the code snippet using logical operators works in a similar fashion as the snippet using the ternary operator (for this example), it is important to know that they are not substitutes.</em></p><p><strong>It is much safer to use the <em>ternary operator</em> for cases like this except you really know what you are doing.</strong></p><p>Consider the following code snippet to understand the danger of using logical operators for cases like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6873d327e6bd339787464fbe1ee4af37/href">https://medium.com/media/6873d327e6bd339787464fbe1ee4af37/href</a></iframe><p>Here is another very familiar conditional statement that was usually found in cross-browser AJAX libraries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2df5e43e09a44ad6c5b9dd1f2d97c034/href">https://medium.com/media/2df5e43e09a44ad6c5b9dd1f2d97c034/href</a></iframe><p>Using logical operators, the previous code snippet can be rewritten like this (<em>indentations are used to aid readability</em>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5aa2b6aff2a462d0bcba96ee325a58ac/href">https://medium.com/media/5aa2b6aff2a462d0bcba96ee325a58ac/href</a></iframe><p>However, using the ternary operator, it can be written like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fb0f91637a3e357d19f5c80e2a5c43f/href">https://medium.com/media/0fb0f91637a3e357d19f5c80e2a5c43f/href</a></iframe><p><em>Notice in this code snippet that the ternary operator is nested, which is useful for dealing with more involved </em><em>if...else conditions</em>.</p><h3>Tips and Shortcuts</h3><p>In this section, you will see some helpful tips and shortcuts that can be useful when working with conditions and logical operators.</p><h4>Normalizing to Boolean</h4><p>You have already seen how to explicitly convert a JavaScript value to its equivalent boolean value, either by using the native Boolean function or by using the <em>double </em><strong><em>NOT</em></strong> (!!) operators.</p><p>Let’s say you want to normalize value such that you always get a boolean as follows:</p><ul><li>If value is a boolean, return value as it is.</li><li>If value is not a boolean, default to a boolean value of your choice - either true or false.</li></ul><p>The following code snippet shows how this can be done (<em>functions are being used here</em>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a64f5d56c2291159ccaae24aadadbed/href">https://medium.com/media/6a64f5d56c2291159ccaae24aadadbed/href</a></iframe><h4>De Morgan’s Laws</h4><p>If you are familiar with Boolean Algebra you should already know about the <strong><em>De Morgan’s</em></strong><em> laws</em>. These laws also apply to JavaScript logical operators.</p><p>The following code snippet demonstrates the laws:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63340e7af620e631031fb77fbfe67a10/href">https://medium.com/media/63340e7af620e631031fb77fbfe67a10/href</a></iframe><h4>Boolean Identities</h4><p>When dealing with booleans, there are some known identities that are always true. Given that A, B and C are boolean values, the following code snippet shows some of these identities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d8fe6b6a3e61ef539233e56e95fceb5/href">https://medium.com/media/3d8fe6b6a3e61ef539233e56e95fceb5/href</a></iframe><h4>Multiple Ternary Operators</h4><p>You have seen in an earlier code snippets that ternary operators can be nested to handle more involved if...else conditional logic.</p><p>However, there are a few things you need to know about the precedence and associativity of the ternary operator to enable you use them effectively in complex expressions.</p><ul><li><strong>The ternary operator has a <em>lower precedence</em> than logical operators and most other operators</strong>. Hence it is evaluated last when used together with operators of higher precedence.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1c695c937d1653b80fe5391cd792a7d/href">https://medium.com/media/b1c695c937d1653b80fe5391cd792a7d/href</a></iframe><ul><li><strong>The ternary operator has a <em>right-to-left</em> associativity</strong>. Hence, when multiple ternary operators are used in the same expression, they are parsed from right to left.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/914f142433f0d3d2da67d80708f567cc/href">https://medium.com/media/914f142433f0d3d2da67d80708f567cc/href</a></iframe><p>When using multiple ternary operators in an expression, you may need to use parentheses (()) to alter the evaluation order. Here is an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6420f4f786db63243cac845afe4da02e/href">https://medium.com/media/6420f4f786db63243cac845afe4da02e/href</a></iframe><h3>More JavaScript for Experts</h3><p>If you are interested in related articles that expose other ways you can improve your JavaScript codes, then don’t hesitate to go through these articles:</p><ol><li><a href="https://codeburst.io/cool-javascript-shortcuts-and-tips-for-everyday-use-66cd174ab216"><strong>Cool JavaScript Shortcuts and Tips for Everyday Use</strong></a></li><li><a href="https://medium.freecodecamp.org/https-medium-com-gladchinda-hacks-for-creating-javascript-arrays-a1b80cb372b"><strong>Hacks for Creating JavaScript Arrays</strong></a></li><li><a href="https://blog.logrocket.com/javascript-es6-5-new-abstractions-to-improve-your-code-54a369e82407"><strong>JavaScript ES6: 5 new abstractions to improve your code</strong></a></li><li><a href="https://codeburst.io/es6-destructuring-the-complete-guide-7f842d08b98f"><strong>ES6 Destructuring: The Complete Guide</strong></a></li><li><a href="https://blog.logrocket.com/javascript-typeof-2511d53a1a62"><strong>JavaScript typeof</strong></a></li></ol><h3>Conclusion</h3><p>Having reached the end of this article, I’m sure you can now be able to identify areas in your code where these tips and techniques can be applied to improve your code like that of an expert.</p><h4>Clap &amp; Follow</h4><p>If you found this article insightful, feel free to give some rounds of applause if you don’t mind.</p><p>You can also follow me on Medium (<a href="https://medium.com/u/ddcd0e9719e5">Glad Chinda</a>) for more insightful articles you may find helpful. You can also follow me on Twitter (<a href="https://twitter.com/@gladchinda">@gladchinda</a>).</p><p><strong><em>Enjoy coding…</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2aa456ef67c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/conditional-javascript-for-experts-d2aa456ef67c">Conditional JavaScript for Experts</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacks for Creating JavaScript Arrays]]></title>
            <link>https://medium.com/free-code-camp/https-medium-com-gladchinda-hacks-for-creating-javascript-arrays-a1b80cb372b?source=rss-ddcd0e9719e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1b80cb372b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[hacks]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Glad Chinda]]></dc:creator>
            <pubDate>Wed, 18 Jul 2018 22:59:31 GMT</pubDate>
            <atom:updated>2019-04-15T12:27:34.767Z</atom:updated>
            <content:encoded><![CDATA[<h4>Insightful tips for creating and cloning arrays in JavaScript.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ikt9LNJUhCX7QxbjnwKstA.png" /><figcaption>Original Photo by <a href="https://unsplash.com/photos/FXFz-sW0uwo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a> on <a href="https://unsplash.com/search/photos/code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A very important aspect of every programming language is the data types and structures available in the language. Most programming languages provide data types for representing and working with complex data. If you have worked with languages like Python or Ruby, you should have seen data types like <strong>lists</strong>, <strong>sets</strong>, <strong>tuples</strong>, <strong>hashes</strong>, <strong>dicts</strong>, and so on.</p><p>In JavaScript, there are not so many complex data types — you simply have <strong>arrays</strong> and <strong>objects</strong>. However, in ES6, a couple of data types and structures were added to the language, such as <strong>symbols</strong>, <strong>sets</strong>, and <strong>maps</strong>.</p><blockquote><em>Arrays in JavaScript are high-level list-like objects with </em>a length property and <em>integer properties as indexes.</em></blockquote><p>In this article, I share a couple of hacks for creating new JavaScript arrays or cloning already existing ones.</p><h3>Creating Arrays: The Array Constructor</h3><p>The most popular method for creating arrays is using the <strong>array literal</strong> syntax, which is very straightforward. However, when you want to dynamically create arrays, the array literal syntax may not always be the best method. An alternative method is using the Array constructor.</p><p>Here is a simple code snippet showing the use of the Array constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74c06cf0f6445671739b9e7a6eabac58/href">https://medium.com/media/74c06cf0f6445671739b9e7a6eabac58/href</a></iframe><p>From the previous snippet, we can see that the Array constructor creates arrays differently depending on the arguments it receives.</p><h3>New Arrays: With Defined Length</h3><p>Let’s look more closely at what happens when creating a new Array of a given length. The constructor just sets the length property of the array to the given length, without setting the keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zAVDoIEPMic-YDgFCe8CJw.png" /></figure><p>From the above snippet, you may be tempted to think that each key in the array was set to a value of undefined. But the reality is that those keys were never set (they don’t exist).</p><p>The following illustration makes it clearer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwhPC9_0jAmpEA5FwcGgEg.png" /></figure><p>This makes it useless to attempt to use any of the array iteration methods such as map(), filter() or reduce() to manipulate the array. Let’s say we want to fill each index in the array with the number 5 as a value. We will attempt the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEzOvF8kktdGYj5zsC2zXA.png" /></figure><p>We can see that map() didn’t work here, because the index properties don’t exist on the array — only the length property exists.</p><p>Let’s see different ways we can fix this issue.</p><h4>1. Using Array.prototype.fill()</h4><p>The <strong>fill()</strong> method fills all the elements of an array from a start index to an end index with a static value. The end index is not included. You can learn more about fill() <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill">here</a>.</p><p><strong>Note that </strong><strong>fill() will only work in browsers with ES6 support.</strong></p><p>Here is a simple illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5ksaIGIrDYFP-KGOR0dwQ.png" /></figure><p>Here, we have been able to fill all the elements of our created array with 5. You can set any static value for different indexes of the array using the fill() method.</p><h4>2. Using Array.from()</h4><p>The <strong>Array.from()</strong> method creates a new, shallow-copied Array instance from an array-like or iterable object. You can learn more about Array.from() <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from">here</a>.</p><p><strong>Note that </strong><strong>Array.from() will only work in browsers with ES6 support.</strong></p><p>Here is a simple illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4EPrjd2az8UDmwmjwEHqg.png" /></figure><p>Here, we now have true undefined values set for each element of the array using Array.from(). This means we can now go ahead and use methods like .map() and .filter() on the array, since the index properties now exist.</p><p>One more thing worth noting about Array.from() is that it can take a second argument, which is a <strong>map function.</strong> It will be called on every element of the array. This makes it redundant calling .map() after Array.from().</p><p>Here is a simple example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ooseeFvTCATj8kZq_137SQ.png" /></figure><h4>3. Using the Spread Operator</h4><p>The <strong>spread operator</strong><em> </em>(...), added in ES6, can be used to spread the elements of the array, setting the missing elements to a value of undefined. This will produce the same result as simply calling Array.from() with just the array as the only argument.</p><p>Here is a simple illustration of using the spread operator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5x4zuSweANx0Wtv0WiKZQ.png" /></figure><p>You can go ahead and use methods like .map() and .filter() on the array, since the index properties now exist.</p><h3>Using Array.of()</h3><p>Just like we saw with creating new arrays using the Array constructor or function, <strong>Array.of()</strong> behaves in a very similar fashion. In fact, the only difference between Array.of() and Array is in how they handle a single integer argument passed to them.</p><p>While <strong>Array.of(5)</strong> creates a new array with a single element, 5, and a length property of 1, <strong>Array(5)</strong> creates a new empty array with 5 empty slots and a length property of 5.</p><pre>var array1 = Array.of(5); // [5]<br>var array2 = Array(5); // Array(5) {length: 5}</pre><p>Besides this major difference, Array.of() behaves just like the Array constructor. You can learn more about Array.of() <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of">here</a>.</p><p><strong>Note that </strong><strong>Array.of() will only work in browsers with ES6 support.</strong></p><h3>Converting to Arrays: Array-likes and Iterables</h3><p>If you have been writing JavaScript functions long enough, you should already know about the arguments object — which is an <strong>array-like</strong> object available in every function to hold the list of arguments the function received. Although the arguments object looks much like an array, it does not have access to the Array.prototype methods.</p><p>Prior to ES6, you would usually see a code snippet like the following when trying to convert the arguments object to an array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*snPxkRQn0hx3UKDSK4b47A.png" /></figure><p>With Array.from() or the spread operator, you can conveniently convert any array-like object into an array. Hence, instead of doing this:</p><pre>var args = Array.prototype.slice.call(arguments);</pre><p>you can do either of these:</p><pre>// Using Array.from()<br>var args = Array.from(arguments);</pre><pre>// Using the Spread operator<br>var args = [...arguments];</pre><p>These also apply to <strong>iterables</strong> as shown in the following illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9EIofn-e9Q8ArZHzSZUaiw.png" /></figure><h3>Case Study: Range Function</h3><p>As a case study before we proceed, we will create a simple <strong>range()</strong> function to implement the new <strong>array hack</strong> we just learned. The function has the following signature:</p><pre>range(start: number, end: number, step: number) =&gt; Array&lt;number&gt;</pre><p>Here is the code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71065ae86b233451a3dce3314338a308/href">https://medium.com/media/71065ae86b233451a3dce3314338a308/href</a></iframe><p>In this code snippet, we used Array.from() to create the new range array of dynamic length and then populate it sequentially incremented numbers by providing a mapping function.</p><p><strong>Note that the above code snippet will not work for browsers without ES6 support except if you use polyfills.</strong></p><p>Here are some results from calling the <strong>range()</strong> function defined in the above code snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fE7w1e5jYBhqmVwb-vVS2A.png" /></figure><p>You can get a live code demo by running the following pen on <strong>Codepen</strong>:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fgladchinda%2Fembed%2Fpreview%2FQxeXzm%3Fheight%3D600%26slug-hash%3DQxeXzm%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fgladchinda%2Fpen%2FQxeXzm%3Feditors%3D0112&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1643031.QxeXzm.small.d0829bc7-b66f-446b-b55d-9c959c2285a7.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8029f5ba147ce7e786421c9421698cc/href">https://medium.com/media/c8029f5ba147ce7e786421c9421698cc/href</a></iframe><h3>Cloning Arrays: The Challenge</h3><p>In JavaScript, arrays and objects are reference types. This means that when a variable is assigned an array or object, what gets assigned to the variable is a reference to the location in memory where the array or object was stored.</p><p>Arrays, just like every other object in JavaScript, are reference types. <strong>This means that arrays are copied by reference and not by value.</strong></p><p>Storing reference types this way has the following consequences:</p><h4><strong>1. Similar arrays are not equal.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rf7nZjxJRdy73T1z0KRRUw.png" /></figure><p>Here, we see that although array1 and array2 contain seemingly the same array specifications, they are not equal. This is because the reference to each of the arrays points to a different location in memory.</p><h4><strong>2. Arrays are copied by reference and not by value.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JI4dqHiukwO_HZvu78h4gg.png" /></figure><p>Here, we attempt to copy array1 to array2, but what we are basically doing is pointing array2 to the same location in memory that array1 points to. Hence, both array1 and array2 point to the same location in memory and are equal.</p><p>The implication of this is that when we make a change to array2 by removing the last item, the last item of array1 also gets removed. This is because the change was actually made to the array stored in memory, whereas array1 and array2 are just pointers to that same location in memory where the array is stored.</p><h3>Cloning Arrays: The Hacks</h3><h4><strong>1. Using Array.prototype.slice()</strong></h4><p>The <strong>slice()</strong> method creates a shallow copy of a portion of an array without modifying the array. You can learn more about slice() <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">here</a>.</p><p>The trick is to call slice() either with0 as the only argument or without any arguments at all:</p><pre>// with O as only argument<br>array.slice(0);</pre><pre>// without argument<br>array.slice();</pre><p>Here is a simple illustration of cloning an array with slice():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eq0aNbde9egoV2SoqC_dZg.png" /></figure><p>Here, you can see that array2 is a clone of array1 with the same items and length. However, they point to different locations in memory, and as a result are not equal. You also notice that when we make a change to array2 by removing the last item, array1 remains unchanged.</p><h4><strong>2. Using Array.prototype.concat()</strong></h4><p>The <strong>concat()</strong> method is used to merge two or more arrays, resulting in a new array, while the original arrays are left unchanged. You can learn more about concat() <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat">here</a>.</p><p>The trick is to call concat() either with an empty array([]) as argument or without any arguments at all:</p><pre>// with an empty array<br>array.concat([]);</pre><pre>// without argument<br>array.concat();</pre><p>Cloning an array with concat() is quite similar to using slice(). Here is a simple illustration of cloning an array with concat():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0WwrsYWuAPXL88Dpek5Bw.png" /></figure><h4>3. Using Array.from()</h4><p>Like we saw earlier, <strong>Array.from()</strong> can be used to create a new array which is a shallow-copy of the original array. Here is a simple illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7kITGQDkqZECJE3eaV57A.png" /></figure><h4>4. Using Array Destructuring</h4><p>With ES6, we have some more powerful tools in our toolbox such as <strong>destructuring</strong>, <strong>spread</strong><em> </em><strong>operator</strong>, <strong>arrow functions</strong>, and so on. Destructuring is a very powerful tool for extracting data from complex types like arrays and objects.</p><blockquote><strong><em>You can learn more about destructuring from </em></strong><a href="https://codeburst.io/es6-destructuring-the-complete-guide-7f842d08b98f"><strong>this article</strong></a><strong><em>.</em></strong></blockquote><p>The trick is to use a technique called <strong>rest parameters,</strong> which involves a combination of array destructuring and the spread operator as shown in the following snippet:</p><pre>let [...arrayClone] = originalArray;</pre><p>The above snippet creates a variable named arrayClone which is a clone of the originalArray. Here is a simple illustration of cloning an array using array destructuring:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ytqfhwrc5bgGInN60FZFQ.png" /></figure><h3>Cloning: Shallow versus Deep</h3><p>All the array cloning techniques we’ve explored so far produce a <strong><em>shallow copy</em></strong> of the array. This won’t be an issue if the array contains only primitive values. However, if the array contains nested object references, those references will remain intact even when the array is cloned.</p><p>Here is a very simple demonstration of this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*84iTgt7bBSOtgykrg39dcg.png" /></figure><p>Notice that modifying the nested array in array1 also modified the nested array in array2 and vice-versa.</p><p>The solution to this problem is to create a <strong><em>deep copy</em></strong> of the array and there are a couple of ways to do this.</p><h4>1. The JSON technique</h4><p>The easiest way to create a deep copy of an array is by using a combination of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify"><strong>JSON.stringify()</strong></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse"><strong>JSON.parse()</strong></a>.</p><p>JSON.stringify() converts a JavaScript value to a valid JSON string, while JSON.parse() converts a JSON string to a corresponding JavaScript value or object.</p><p>Here is a simple example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g744L7K69apazaPNXjscvQ.png" /></figure><blockquote>The JSON technique has some flaws especially when values other than strings, numbers and booleans are involved.</blockquote><p>These flaws in the JSON technique can be majorly attributed to the manner in which the JSON.stringify() method converts values to JSON string.</p><p>Here is a simple demonstration of this flaw in trying to <strong>JSON.stringify()</strong> a value containing nested function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCvVYv9I4woeqU3i6LuB8Q.png" /></figure><h4>2. Deep Copy Helper</h4><p>A viable alternative to the JSON technique will be to implement your own <strong><em>deep copy helper function</em></strong> for cloning reference types whether they be arrays or objects.</p><p>Here is a very simple and minimalistic deep copy function called <strong>deepClone</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b6fdca7847526a46a3eeb7f8a4aeea2/href">https://medium.com/media/5b6fdca7847526a46a3eeb7f8a4aeea2/href</a></iframe><p>Now this is not the best of deep copy functions out there, like you will soon see with some JavaScript libraries — however, it performs deep copying to a pretty good extent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkgxvywrostFOYj0vJjrHg.png" /></figure><h4>3. Using JavaScript Libraries</h4><p>The deep copy helper function we just defined is not robust enough in cloning all the kinds of JavaScript data that may be nested within complex objects or arrays.</p><p>JavaScript libraries like <a href="https://lodash.com/"><strong>Lodash</strong></a> and <a href="https://jquery.com/"><strong>jQuery</strong></a> provide more robust deep copy utility functions with support for different kinds of JavaScript data.</p><p>Here is an example that uses <strong>_.cloneDeep()</strong> from the Lodash library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJIos6PerF0nWe_74wQj5g.png" /></figure><p>Here is the same example but using <strong>$.extend()</strong> from the jQuery library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFzS9yj1W-9m2ruTZSgpXw.png" /></figure><h3>Conclusion</h3><p>In this article, we have been able to explore several techniques for dynamically creating new arrays and cloning already existing ones, including converting array-like objects and iterables to arrays.</p><p>We have also seen how some of the new features and enhancements introduced in ES6 can enable us to effectively perform certain manipulations on arrays.</p><p>We used features like destructuring and the spread operator for cloning and spreading arrays. You can learn more about destructuring from <a href="https://codeburst.io/es6-destructuring-the-complete-guide-7f842d08b98f">this article</a>.</p><h4>Clap &amp; Follow</h4><p>If you found this article insightful, you are free to give some rounds of applause if you don’t mind.</p><p>You can also follow me on Medium (<a href="https://medium.com/u/ddcd0e9719e5">Glad Chinda</a>) for more insightful articles you may find helpful. You can also follow me on Twitter (<a href="https://twitter.com/@gladchinda">@gladchinda</a>).</p><p><strong><em>Happy hacking…</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1b80cb372b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/https-medium-com-gladchinda-hacks-for-creating-javascript-arrays-a1b80cb372b">Hacks for Creating JavaScript Arrays</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cool JavaScript Shortcuts and Tips for Everyday Use]]></title>
            <link>https://codeburst.io/cool-javascript-shortcuts-and-tips-for-everyday-use-66cd174ab216?source=rss-ddcd0e9719e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/66cd174ab216</guid>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Glad Chinda]]></dc:creator>
            <pubDate>Fri, 01 Jun 2018 12:42:02 GMT</pubDate>
            <atom:updated>2019-04-08T13:17:43.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vd-SOfeIbO1u_JMPvPn27Q.jpeg" /><figcaption><a href="https://www.flickr.com/photos/132053576@N03/18721001439">Image from Flickr</a>. Photo credit: <a href="http://www.homewatersoftenerreviews.com/">Home Water Softener Reviews</a></figcaption></figure><p>JavaScript has been around for quite sometime now. Although, it only started becoming very popular in the last few years. The results of <a href="https://insights.stackoverflow.com/survey/2017">surveys conducted by StackOverflow in 2017</a> prove JavaScript to be the most commonly used programming language. With almost <em>75% of developers in the world being web developers</em>, there is a <strong>very high chance that 3 out of every 5 developers use JavaScript</strong>.</p><p>For the few years I have worked with JavaScript, there are a few JavaScript shortcuts I tend to use often. In this article, I will be sharing a couple of them, hoping that a few JavaScript developers out there will find them useful.</p><h3>1. Values: truthy and falsy</h3><p>Most new JavaScript developers may be aware of the built-in data types in JavaScript. However, not so many may know about JavaScript’s classification of <strong>truthy<em> </em></strong>and<strong><em> </em></strong><strong>falsy<em> </em></strong>values.</p><p>Anytime JavaScript expects a <strong>boolean</strong> value, a <strong>truthy<em> </em></strong>value will behave like <strong>true</strong>, whereas a <strong>falsy<em> </em></strong>value works like <strong>false</strong>. These are the <em>falsy values</em>:</p><ol><li>0</li><li>-0</li><li>null</li><li>undefined</li><li>&#39;&#39;</li><li>NaN</li><li>false</li></ol><p>As you can see, even an <strong>empty string</strong> is considered a <em>falsy</em><strong><em> </em></strong>value. All other values besides the above mentioned are <em>truthy</em> values.</p><p>The <strong>!</strong> operator can be used to convert any value to a <strong>boolean</strong>. When using the <strong>!</strong> operator with values, <em>truthy </em>values evaluate to <strong>false</strong>, while <em>falsy </em>values evaluate to <strong>true</strong>. You can use the double (<strong>!!</strong>) operator to get the corresponding <strong>boolean</strong> for any value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d520b8f115edf898c276f0eb350d8cb0/href">https://medium.com/media/d520b8f115edf898c276f0eb350d8cb0/href</a></iframe><p>Let’s say a variable <strong>person</strong> can either contain an <strong>object</strong> or <strong>null</strong>. You can verify that the person variable is not <strong>null</strong>, by using the following condition:</p><pre>if (person !== null) { ... }</pre><p>Considering that <strong>null</strong> is <em>falsy </em>while every other object is <em>truthy</em>, you can use this (<em>less strict condition</em>):</p><pre>if (person) { ... }</pre><h3>2. Type Conversion: Number and String</h3><p>One of the most common things you find yourself doing in JavaScript is using arithmetic operators: <strong>+</strong>, <strong>-</strong>, <strong>*</strong>, <strong>/</strong>. These operators expect operands that are numbers. So when any of the operands is not a <strong>number</strong>, JavaScript implicitly coerces it into a <strong>number</strong>. But there are times when you may not get the result you may be expecting, especially when you are using the <strong>+</strong> operator. This is majorly because the <strong>+</strong> operator is also used for <em>string concatenation</em>. See the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fea35ff884fe9c73ca008f0e3717ecd/href">https://medium.com/media/7fea35ff884fe9c73ca008f0e3717ecd/href</a></iframe><p>As you can see, <em>implicit type coercion</em> may not always give you the result you are expecting. This is because of how JavaScript handles type conversion especially for objects. The difference is due to the order in which JavaScript calls the <strong>toString()</strong> and <strong>valueOf()</strong> methods on the object for <em>object-to-primitive</em> conversion.</p><p>Now here is the trick. The <strong>+</strong> operator when used as a <em>unary operator</em> always converts its operand to a <strong>number</strong>. Hence, the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eeb0c229c1a6a52481da03e8b3c0244/href">https://medium.com/media/2eeb0c229c1a6a52481da03e8b3c0244/href</a></iframe><p>Using the unary <strong>+</strong> operator on a value is functionally equivalent to casting the value using the <strong>Number()</strong> function.</p><pre>+new Date === Number(new Date); // true</pre><p>The <strong>+</strong> operator can also be used to convert values to <strong>string</strong>. Concatenate an empty string(<strong>&#39;&#39;</strong>) to any value using the <strong>+</strong> operator to convert the value to a <strong>string</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e5da5d7eede60785cc3aaa350ffdf5e/href">https://medium.com/media/6e5da5d7eede60785cc3aaa350ffdf5e/href</a></iframe><p>Using the <strong>+</strong> operator to convert values to <strong>string</strong> is functionally equivalent to casting values to string using the <strong>String()</strong> function.</p><pre>([100, 50] + &#39;&#39;) === String([100, 50]); // true</pre><h3>3. Short-Circuiting</h3><p>When working with the (<strong>||</strong> and <strong>&amp;&amp;</strong>) logical operators, you may have noticed an interesting behavior called <em>short-circuiting</em>. Here is how it works:</p><p><strong><em>The logical </em></strong><strong><em>&amp;&amp; operator returns the first operand if it is </em></strong><strong><em>falsy, otherwise it returns the second operand.</em></strong></p><p>The logical <strong>&amp;&amp;</strong> short-circuiting is commonly used as a replacement for very simple <strong>if</strong> statements as shown in the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f15996c93aaf1762c5e34cc15721ad7b/href">https://medium.com/media/f15996c93aaf1762c5e34cc15721ad7b/href</a></iframe><p>Note that using <strong><em>short-circuiting actually returns a value</em></strong> since it is a JavaScript expression. Hence, the result of a short-circuiting operation can be stored in a variable or used anywhere JavaScript expects a value.</p><pre>var personProfile = person &amp;&amp; fetchProfile(person);</pre><p>However, using <strong>if</strong> statement does not return a value because it is a JavaScript statement.</p><p><strong><em>The logical </em></strong><strong><em>|| operator returns the first operand if it is </em></strong><strong><em>truthy, otherwise it returns the second operand.</em></strong></p><p>The logical <strong>||</strong> short-circuiting is commonly used when assigning fallback values to local variables as shown in the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35c0f09b282fe583192325106792a1d2/href">https://medium.com/media/35c0f09b282fe583192325106792a1d2/href</a></iframe><p>In the following snippet, <em>short-circuiting </em>is used to create two functions that always return a <strong>boolean</strong> value. If the first argument is a <strong>boolean</strong> value, it is returned, otherwise the desired fallback <strong>boolean</strong> value is returned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48702e615964bf544e76cb05859ab9b9/href">https://medium.com/media/48702e615964bf544e76cb05859ab9b9/href</a></iframe><h3>4. Ternary Operator</h3><p>The ternary operator can be used as a substitute for very simple <strong>if/else</strong> statements. Here is the syntax:</p><pre>(condition) ? (return value if truthy) : (return value if falsy)</pre><p>The ternary operation requires 3 operands. The first is a <strong>condition</strong> value or expression. The second is a value or expression that is evaluated and returned if the condition is truthy. The third is a value or expression that is evaluated and returned if the condition is falsy.</p><p>Here is a quick example showing how to use the ternary operation as a shortcut for simple <strong>if/else</strong> statements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7e743ed312adfd25edab64c1e50af23/href">https://medium.com/media/a7e743ed312adfd25edab64c1e50af23/href</a></iframe><p>This feels good already, but it gets more interesting knowing that ternary operations can be nested. The ternary operator has a <em>right-to-left</em> associativity. Hence, the following expression:</p><pre>a ? b : c ? d : e ? f : g</pre><p>is evaluated as:</p><pre>(a ? b : (c ? d : (e ? f : g)))</pre><p>Nested ternary operations can be used as alternatives to multiple <strong>if/else</strong> statements. Here is a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6539e7841320ed8a4ad1b661b302098b/href">https://medium.com/media/6539e7841320ed8a4ad1b661b302098b/href</a></iframe><p>Notice how concise the ternary operation is in comparison to using multiple <strong>if/else</strong> statements.</p><p>Note that the <strong><em>ternary operation returns a value</em></strong> since it is a JavaScript expression. Hence, the result of a ternary operation can be stored in a variable or used anywhere JavaScript expects a value. That is the reason why the value of the ternary operation could be returned from the <strong>boundedValue()</strong> function.</p><h3>5. Working with Numbers</h3><h4>Random Numbers</h4><p>As a JavaScript developer, it is possible that you have used <strong>Math.random()</strong> at one point or the other. The <strong>Math.random()</strong> function returns a floating-point, pseudo-random number in the range from 0 inclusive up to but not including 1.</p><pre>console.log(Math.random()); // 0.684408535330514</pre><p>If you want to create a random floating-point number in the range from 0 inclusive up to but not including let’s say 10, you multiply <strong>Math.random()</strong> by <strong>10</strong>.</p><pre>console.log(Math.random() * 10); // 8.368613312939646</pre><p><strong>Math.random()</strong> when combined with other functions like <strong>Math.floor()</strong> or <strong>Math.ceil()</strong> can be used for some cool number generation combos.</p><p>Here is a simple function that generates a random integer from <strong>1</strong> to the given <strong>maxvalue</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b18c1f4056ce45d225cd6fd8069af7a/href">https://medium.com/media/3b18c1f4056ce45d225cd6fd8069af7a/href</a></iframe><h4><strong>Min/Max Numbers</strong></h4><p>The <strong>Math.min()</strong> and <strong>Math.max()</strong> functions also come in very handy when trying to deal with bounded numbers. For example the previous <strong>boundedValue()</strong> example can be implemented using <strong>Math.min()</strong> and <strong>Math.max()</strong> as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19d551820bdcb2842f04be1c7e4382da/href">https://medium.com/media/19d551820bdcb2842f04be1c7e4382da/href</a></iframe><h4>Number Base Conversion</h4><p>In JavaScript, <strong><em>number literals are primitives</em></strong>. However, you can access any method available on number objects created using the <strong>Number()</strong> constructor, one of which is <strong>toString()</strong>.</p><p>The <strong>Number.prototype.toString()</strong> method accepts a <strong>radix</strong> integer argument which specifies the base to which the number must be converted. If this argument is not specified, it defaults to <strong>10</strong>, which means the number is left the same way and then converted to a string.</p><p>Hence, you can convert a number to different bases as shown in the following snippet:</p><pre>(255).toString(); // &quot;255&quot;<br>(255).toString(2); // &quot;11111111&quot;<br>(255).toString(8); // &quot;377&quot;<br>(255).toString(16); // &quot;ff&quot;</pre><p>Cool huh? The following snippet shows a function <strong>rgbToHex()</strong> for converting <strong><em>RGB color value</em></strong> to <strong><em>hex color value</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ba0cefaa284fb5f618ad15ee26f6970/href">https://medium.com/media/8ba0cefaa284fb5f618ad15ee26f6970/href</a></iframe><h3>Conclusion</h3><p>In this article, I have shared a couple of JavaScript tips and shortcuts that you may find very helpful at certain points while writing JavaScript programs.</p><p>If none of the tips shared in this article is new to you, then that’s really lovely. However, if you are one of the few people who adopted a thing or two from this article, then I’m glad you did find it helpful. <strong><em>Do well to give some rounds of applause in that case</em></strong>.</p><p>You can also follow me on Twitter at <a href="https://twitter.com/gladchinda">@gladchinda</a> and on Medium as I share more contents you may find helpful.</p><p><strong><em>Happy Coding…</em></strong></p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66cd174ab216" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/cool-javascript-shortcuts-and-tips-for-everyday-use-66cd174ab216">Cool JavaScript Shortcuts and Tips for Everyday Use</a> was originally published in <a href="https://codeburst.io">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reacting Responsively]]></title>
            <link>https://codeburst.io/reacting-responsively-d81812d1e7d?source=rss-ddcd0e9719e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d81812d1e7d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[responsive-design]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Glad Chinda]]></dc:creator>
            <pubDate>Mon, 23 Apr 2018 13:23:57 GMT</pubDate>
            <atom:updated>2018-09-25T11:47:17.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52PxCpm--R9ObLRb3otx6w.jpeg" /><figcaption><em>Original photo was gotten from </em><a href="https://pixabay.com/en/responsive-web-web-design-websites-2044921/"><strong><em>PixaBay</em></strong></a><strong><em> </em></strong><em>and slightly modified.</em></figcaption></figure><p>Can you forget about the title of this article for a moment? The article you are about to read has nothing to do with a <strong><em>chemical reaction</em></strong> or how you <strong><em>react to circumstances</em></strong>. However, it has everything to do with <strong><em>React applications</em></strong>.</p><p><strong>What does Reacting Responsively even mean?</strong></p><p>It’s simply the title of the article you are reading. Jokes apart, you can take it to mean <strong><em>the technique of building responsive-aware components in React applications</em></strong>. This usually involves what I would call <strong><em>responsive rendering</em></strong>. We will get back to this in a moment.</p><h4>Responsive Design</h4><p>Responsive design is not a new concept. If you’ve been around for sometime in the web development space there is very high chance you already know what this means. <strong><em>Responsive design simply is the technique of designing user interfaces that can adapt to different screen sizes</em></strong><em>.</em></p><p><strong>What usually comes to your mind when you hear responsive design?</strong></p><p>For the majority of front-end engineers, it is likely CSS <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries"><strong><em>media queries</em></strong></a>, which is one of the most fundamental aspects of responsive design.</p><p>For some others, it could be one of the plethora of CSS frameworks — like <a href="https://getbootstrap.com/"><strong>Bootstrap</strong></a>, <a href="https://foundation.zurb.com/"><strong>Foundation</strong></a>, <a href="https://bulma.io/"><strong>Bulma</strong></a>, etc — since virtually all CSS frameworks have built-in responsive design utilities.</p><p>In fact, if you have ever heard of <a href="https://www.uxpin.com/studio/blog/a-hands-on-guide-to-mobile-first-design/"><strong><em>mobile-first design</em></strong></a>, then you have heard of responsive design in disguise, because that’s what it’s all about.</p><p>While our focus isn’t on doing a detailed exposé on responsive design, we will however take a look at <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries"><strong><em>media queries</em></strong></a>, since it is one of the most fundamental aspects of responsive design, and also the concept on which this article is based.</p><p>Here is what a typical media query looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e76e3c3e240749b2d4bb1cf2439c4233/href">https://medium.com/media/e76e3c3e240749b2d4bb1cf2439c4233/href</a></iframe><p><strong>Yay, we finally got to write some code</strong>. Here we are simply defining display styles for a fictitious .app-nav element on our app that is meant to display the navigation menu for the app.</p><p><strong>First</strong>, we set the initial styles to display the <em>mobile-friendly version</em> of the navigation element with the .mobile class and hide the full version for wider screens.</p><p><strong>Then</strong>, we use a <em>media query</em> to ensure that the full version is displayed for screens with viewport width as wide as or wider than 992px instead of the mobile version.</p><p>Some advanced CSS frameworks like <a href="https://getbootstrap.com/"><strong>Bootstrap</strong></a> even make it possible to achieve something this simple using the built-in responsive classes in your app markup, without having to write a single line of CSS.</p><p>For example, with <strong>Bootstrap 4</strong>, all we have to do to achieve the same effect is to change our markup to look like the following snippet <strong><em>(no CSS required)</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e2093ce98bee4d30757ce38fab73cb6/href">https://medium.com/media/4e2093ce98bee4d30757ce38fab73cb6/href</a></iframe><p>Here, we use some of the built-in responsive classes in Bootstrap to achieve the same effect without writing any CSS. Bootstrap uses the concept of <a href="https://getbootstrap.com/docs/4.0/layout/overview/#responsive-breakpoints"><strong>breakpoints</strong></a><strong> </strong>to classify screen sizes based on viewport width. So <strong><em>large screens</em></strong> are taken to be screens with viewport width <strong><em>greater than or equal to </em>(≥) </strong><strong>992px</strong>.</p><p>The end result is that our app navigation menu is able to adapt to different screen sizes and change it’s display as required. We can simply say <strong><em>our app navigation menu is responsive</em></strong>.</p><h4>Responsive Rendering</h4><p>In the previous examples, each app navigation element remains in the DOM even when it is not displayed. With React, we should be able to prevent those elements that shouldn’t be displayed from rendering in the first place. I call this <strong><em>responsive rendering</em></strong>.</p><p>There are a handful of packages that can be used achieve this in React. But for this article, we will be using the <a href="https://github.com/contra/react-responsive">react-responsive</a> package.</p><p>Here is what our previous example could look like using the react-responsive package in our React application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4093276fa53aa5551f63cf680781fae4/href">https://medium.com/media/4093276fa53aa5551f63cf680781fae4/href</a></iframe><p>Here, we use the media query testing capability provided by the react-responsive package to test the current viewport width and <strong>render only the appropriate navigation menu</strong> for our app — the other versions are not rendered at all.</p><p>The matches parameter of the child function of the MediaQuery component has a value of true if the viewport width is a minimum of 992px, otherwise, its value is false.</p><p>The end result of this <strong><em>responsive rendering</em></strong> is that our React app now renders only the appropriate version of the navigation menu based on the current viewport width.</p><h4>Conclusion</h4><p>In this article, we have been able to move from just designing responsive interfaces using basic CSS media queries and CSS frameworks, to <strong><em>reacting responsively</em></strong> using the <a href="https://github.com/contra/react-responsive">react-responsive</a> package <strong><em>to build responsive-aware React components</em></strong>.</p><p>While we tried to be very simplistic in this article, there are still a lot more advanced stuffs you can do with <a href="https://github.com/contra/react-responsive">react-responsive</a> using complex media query props as suited for your app requirements.</p><p><strong>I do hope you found this article helpful. Happy Coding!!!</strong></p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d81812d1e7d" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/reacting-responsively-d81812d1e7d">Reacting Responsively</a> was originally published in <a href="https://codeburst.io">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 Destructuring: The Complete Guide]]></title>
            <link>https://codeburst.io/es6-destructuring-the-complete-guide-7f842d08b98f?source=rss-ddcd0e9719e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f842d08b98f</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Glad Chinda]]></dc:creator>
            <pubDate>Wed, 18 Apr 2018 13:03:32 GMT</pubDate>
            <atom:updated>2019-06-08T16:00:13.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1s-kJXwWTIhf2-_dOURSg.jpeg" /><figcaption>The Complete Guide to Destructuring in ES6</figcaption></figure><p>JavaScript is currently one of the most used programming languages in the world, being used across different platforms ranging from web browsers, mobile devices, VR, web servers, etc. Although the language has not changed a lot through the years when compared to other programming languages, there are some recent changes that are worth taking note of, because of the expressive power they add to the language — some of which are: <em>template literals</em>, <em>destructuring</em>, <em>spread operator</em>, <em>arrow functions</em>, <em>classes</em>, etc.</p><p>In this tutorial, our major focus will be on learning how to <strong>harness the power of destructuring</strong> to simplify our JavaScript programs. Before we dive into the <strong><em>what</em></strong> and <strong><em>how</em></strong> of destructuring I think the <strong><em>why</em></strong> should be considered. If you already use TypeScript or a modern JavaScript framework like React, Vue, Preact, Angular, etc, you may already be familiar with destructuring. However, there is a possibility that by going through this tutorial, you may learn a few new stuffs about destructuring you may not have known.</p><p>For this tutorial, it is assumed you already have some prior experience writing JavaScript code. There is a chance that some of the code snippets may not work on your browser depending on the version of the browser, since all the ES6 and ES7 features are not yet fully supported in all browsers. You may opt to test the code snippets on <a href="https://codepen.io/"><strong>Codepen</strong></a> or your favorite online JavaScript live editor. Another alternative would be using the <a href="https://babeljs.io/"><strong>Babel transpiler</strong></a> to get it to work on your browser.</p><h3>Why Destructuring?</h3><p>To explain the why of destructuring, we will consider a scenario which most of us might be familiar with or might have come across at one time or the other when coding in JavaScript. Imagine we have the data of a student including scores in three subjects(<em>Maths</em>, <em>Elementary Science</em>, <em>English</em>) represented in an object and we need to display some information based on this data. We could end up with something that looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/610cfe8632a7dad8d8b52688022ab630/href">https://medium.com/media/610cfe8632a7dad8d8b52688022ab630/href</a></iframe><p>With the above code snippet, we would achieve the desired result. However, there are a few caveats to writing code this way. One of which is — you can easily make a <em>typo</em> and instead of writing scores.english for example, you write score.english which will result in an error. Again, if the scores object we are accessing is deeply nested in another object, the object access chain becomes longer which could mean more typing. These may not seem to be much an issue, but with destructuring we can do the same in a more expressive and compact syntax.</p><h3>What is Destructuring?</h3><p><strong>Destructuring simply implies breaking down a complex structure into simpler parts.</strong> In JavaScript, this complex structure is usually an object or an array. With the destructuring syntax, you can extract smaller fragments from arrays and objects. Destructuring syntax can be used for <strong><em>variable declaration</em></strong> or <strong><em>variable assignment</em></strong>. You can also handle nested structures by using nested destructuring syntax.</p><p>Using destructuring, the function from our previous snippet will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d474f7368c919ffff884f3de4ec74bc1/href">https://medium.com/media/d474f7368c919ffff884f3de4ec74bc1/href</a></iframe><p>There is a chance that the code in the last snippet didn’t go down well with you. If that’s the case, then follow up with the tutorial till you get to the end — I assure you it will all make sense. Let’s continue to learn how we can harness the power of destructuring.</p><h3>Object Destructuring</h3><p>What we saw in that last snippet is a form of <strong><em>object destructuring</em></strong> being used as an assignment to a function. Let’s explore what we can do with object destructuring starting from the ground up. Basically, <strong>you use an object literal on the left-hand-side of an assignment expression</strong> for object destructuring. Here is a basic snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b86f33c567f65cd76fde19582900a52/href">https://medium.com/media/2b86f33c567f65cd76fde19582900a52/href</a></iframe><p>Here we used object destructuring syntax to assign values to three variables: firstname, lastname and country using the values from their corresponding keys on the student object. This is the most basic form of object destructuring.</p><p><strong>The same syntax can be used in variable assignment</strong> as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7cc4404bfac9fa1b6d925b9ed178f51/href">https://medium.com/media/f7cc4404bfac9fa1b6d925b9ed178f51/href</a></iframe><p>The above snippet shows how to use object destructuring to assign new values to local variables. Notice that we had to <strong>use a pair of enclosing parentheses (</strong><strong>()) in the assignment expression</strong>. If omitted, the destructuring object literal will be taken to be a block statement, which will lead to an error because a block cannot appear at the left-hand-side of an assignment expression.</p><h4>Default Values</h4><p>Trying to assign a variable corresponding to a key that does not exist on the destructured object will cause the value undefined to be assigned instead. You can pass <strong><em>default values</em></strong> that will be assigned to such variables instead of undefined. Here is a simple example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5d170d70be876c47fbfb63bc2cdfc14/href">https://medium.com/media/a5d170d70be876c47fbfb63bc2cdfc14/href</a></iframe><p>Here we assigned a default value of 25 to the age variable. Since the age key does not exist on the person object, 25 is assigned to the age variable instead of undefined.</p><h4>Using Different Variable Names</h4><p>So far, we have been assigning to variables that have the same name as the corresponding object key. You can assign to a different variable name using this syntax: <strong>[object_key]:[variable_name]</strong>. You can also pass default values using the syntax: <strong>[object_key]:[variable_name] = [default_value]</strong>. Here is a simple example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abf48345513bb16502a00bdfdd87fe5a/href">https://medium.com/media/abf48345513bb16502a00bdfdd87fe5a/href</a></iframe><p>Here we created three local variables namely: fullname, place and years that map to the name, country and age keys respectively of the person object. Notice that we specified a default value of 25 for the years variable in case the age key is missing on the person object.</p><h4>Nested Object Destructuring</h4><p>Referring back to our initial destructuring example, we recall that the scores object is nested in the student object. Let’s say we want to assign the <em>Maths</em> and <em>Science</em> scores to local variables. The following code snippet shows how we can use nested object destructuring to do this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f87771106448d036db25ba6d9f363f48/href">https://medium.com/media/f87771106448d036db25ba6d9f363f48/href</a></iframe><p>Here, we defined three local variables: name, maths and science. Also, we specified a default value of 50 for science in case it does not exist in the nested scores object. Notice that, scores is not defined as a variable. Instead, we use nested destructuring to extract the maths and science values from the nestedscores object.</p><p><strong>When using nested object destructuring, be careful to avoid using an empty nested object literal.</strong> Though it is valid syntax, it actually does no assignment. For example, the following destructuring does absolutely no assignment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bd45f1f42072547a65e0c68b674ceca/href">https://medium.com/media/6bd45f1f42072547a65e0c68b674ceca/href</a></iframe><h3>Array Destructuring</h3><p>By now you are already feeling like a destructuring ninja, having gone through the rigours of understanding object destructuring. The good news is that array destructuring is very much similar and straight forward so let’s dive in right away.</p><p>In array destructuring, <strong>you use an array literal on the left-hand-side of an assignment expression</strong>. Each variable name on the array literal maps to the corresponding item at the same index on the destructured array. Here is a quick example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb523c517b4065db24c17505eea0a9b3/href">https://medium.com/media/bb523c517b4065db24c17505eea0a9b3/href</a></iframe><p>In this example, we have assigned the items in the rgb array to three local variables: red, green and blue using array destructuring. Notice that each variable is mapped to the corresponding item at the same index on the rgb array.</p><h4>Default Values</h4><p>If the number of items in the array is more than the number of local variables passed to the destructuring array literal, then the excess items are not mapped. But if the number of local variables passed to the destructuring array literal exceed the number of items in the array, then each excess local variable will be assigned a value of undefined except you specify a <strong><em>default value</em></strong>.</p><p>Just as with object destructuring, you can set default values for local variables using array destructuring. In the following example, we would set default values for some variables in case a corresponding item is not found.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6797a72e57d3a5f3bf43f70ebe51683/href">https://medium.com/media/d6797a72e57d3a5f3bf43f70ebe51683/href</a></iframe><p>You can also do an <strong>array destructuring assignment</strong>. Unlike with object destructuring, <strong>you don’t need to enclose the assignment expression in parentheses</strong>. Here is an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d583523bfd7923e0f4ba0d6bbb285fc/href">https://medium.com/media/5d583523bfd7923e0f4ba0d6bbb285fc/href</a></iframe><h4>Skipping Items</h4><p>It is possible to skip some items you don’t want to assign to local variables and only assign the ones you are interested in. Here is an example of how we can assign only the blue value to a local variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2358501f22873788a754467c64eaf504/href">https://medium.com/media/2358501f22873788a754467c64eaf504/href</a></iframe><p>We used <em>comma separation</em>(,) to omit the first two items of the rgb array, since we only needed the third item.</p><h4>Swapping Variables</h4><p>One very nice application of array destructuring is in <strong><em>swapping local variables</em></strong>. Imagine you are building a photo manipulation app and you want to be able to swap the height and width dimensions of a photo when the orientation of the photo is switched between landscape and portrait. The old-fashioned way of doing this will look like the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a2965540bebecca4afcf3a8707ddc14/href">https://medium.com/media/3a2965540bebecca4afcf3a8707ddc14/href</a></iframe><p>The above code snippet performs the task, although we had to use an additional variable to copy the value of one of the swapped variables. With array destructuring, we can perform the swap with a single assignment statement. The following snippet shows how array destructuring can be used to achieve this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/062cb4579cd648fc4fd16ef335e9eb8a/href">https://medium.com/media/062cb4579cd648fc4fd16ef335e9eb8a/href</a></iframe><h4>Nested Array Destructuring</h4><p>Just as with objects, you can also do nested destructuring with arrays. The corresponding item must be an array in order to use a nested destructuring array literal to assign items in it to local variables. Here is a quick example to illustrate this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e893248ceca885d576e16162542aeb67/href">https://medium.com/media/e893248ceca885d576e16162542aeb67/href</a></iframe><p>In the code above, we assigned hex variable and used nested array destructuring to assign to the red, green and blue variables.</p><h4>Rest Items</h4><p>Sometimes you may want to assign some items to variables, while ensuring that the remaining items are <strong><em>captured</em></strong><em> </em>(assigned to another local variable). The new <strong>rest parameter </strong>syntax<strong> </strong>(...param) added in ES6 can be used with destructuring to achieve this. Here is a quick example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aafd52d6ac0748a05b61468d43fbe5f6/href">https://medium.com/media/aafd52d6ac0748a05b61468d43fbe5f6/href</a></iframe><p>Here you can see that after we assigned the first and third items of the rainbow array to red and yellow respectively, we used the <em>rest parameters </em>syntax<em> </em>(...param) to capture and assign the remaining values to the otherColors variable. This is referred to as the <strong><em>rest items </em></strong>variable. <strong>Note however that the rest parameter, if used, must always appear as the last item</strong> in the destructuring array literal otherwise an error will be thrown.</p><p>There are some <strong>nice applications of rest items</strong> that are worth considering. One of which is cloning arrays.</p><h4>Cloning Arrays</h4><p>In JavaScript, <strong>arrays are reference types and hence they are assigned by reference instead of being copied</strong>. So in the following snippet, both the rainbow and the rainbowClone variables point to the same array reference in memory and hence any change made to rainbow is also applied to rainbowClone and vice-versa.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96f1126480b491d7d4eee36bb13588fc/href">https://medium.com/media/96f1126480b491d7d4eee36bb13588fc/href</a></iframe><p>The following code snippet shows how we can clone an array in the <strong>old-fashioned(ES5)</strong> way — Array.prototype.slice and Array.prototype.concat to the rescue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3394c65ec75891344033e8bf366d3798/href">https://medium.com/media/3394c65ec75891344033e8bf366d3798/href</a></iframe><p>Here is how you can use <strong>array destructuring</strong> and the <strong>rest parameter syntax </strong>to create an array clone.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21d662fb4649c9233ed3d7bd241277c1/href">https://medium.com/media/21d662fb4649c9233ed3d7bd241277c1/href</a></iframe><h3>Mixed Destructuring</h3><p>There are cases when you are working with a pretty complex object/array structure and you need to assign some values from it to local variables. A good example would be an object with several deeply nested objects and arrays. In cases like this, you can use a combination of object destructuring and array destructuring to target certain parts of the complex structure as required. The following code shows a simple example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53f1ae15cfdff8560633266255747c08/href">https://medium.com/media/53f1ae15cfdff8560633266255747c08/href</a></iframe><h3>Destructured Function Parameters</h3><p>Destructuring can also be applied on function parameters to extract values and assign them to local variables. Note however that the <strong>destructured parameter cannot be omitted (it is required)</strong> otherwise it throws an error. A good use case is the displaySummary() function from our initial example that expects a student object as parameter. We can destructure the student object and assign the extracted values to local variables of the function. Here is the example again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22f41e720440f7720641a65dcb908168/href">https://medium.com/media/22f41e720440f7720641a65dcb908168/href</a></iframe><p>Here we extracted the values we need from the student object parameter and assigned them to local variables: name, maths, english and science. Notice that although we have specified default values for some of the variables, if you call the function with no arguments you will get an error because <strong>destructured parameters are always required</strong>. You can assign a fallback object literal as default value for the student object and the nested scores object in case they are not supplied to avoid the error as shown in the following snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fae3c4d57cef1e04993d691b6de401d/href">https://medium.com/media/7fae3c4d57cef1e04993d691b6de401d/href</a></iframe><h3>Conclusion</h3><p>In this tutorial, we have explored the ES6 destructuring syntax and various ways we can utilize it in our code. If you are already pretty familiar with JavaScript destructuring, you may have learnt a few new stuffs as well. Although we used the rest parameter syntax at several points, it is worth noting that there is still more you can achieve with rest parameters. You can check <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax"><strong>Spread Syntax</strong></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters"><strong>Rest Parameters</strong></a> for more details.</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f842d08b98f" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/es6-destructuring-the-complete-guide-7f842d08b98f">ES6 Destructuring: The Complete Guide</a> was originally published in <a href="https://codeburst.io">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expressive Random Key Generation with Keygen]]></title>
            <link>https://medium.com/@gladchinda/expressive-random-keys-generation-with-keygen-php-9037c585ac8e?source=rss-ddcd0e9719e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9037c585ac8e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel-5]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[php-developers]]></category>
            <dc:creator><![CDATA[Glad Chinda]]></dc:creator>
            <pubDate>Fri, 05 Jan 2018 11:14:13 GMT</pubDate>
            <atom:updated>2018-01-05T13:09:05.059Z</atom:updated>
            <content:encoded><![CDATA[<h4>For PHP Developers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*j-A1n1R4BN_xYqiz4ZFxRg.png" /><figcaption>Randomness everywhere. (Photo from Pixabay)</figcaption></figure><p>Few years back, while working on some PHP applications, I always saw myself needing to generate random strings or numbers to use in a database field, or to use as a random filename or random token, the list goes on. Usually, I would create function libraries to handle that for me. But then, I thought I should just create a package that handles all those functionalities, and then I can plug it into my PHP application if I need it. That’s how the <a href="https://github.com/gladchinda/keygen-php"><strong>Keygen</strong></a> package came to be.</p><blockquote>Keygen is a PHP package for generating simple random character sequences of any desired length. It ships with four generators, namely: <em>numeric</em>, <em>alphanumeric</em>, <em>token </em>and <em>bytes</em>. It has a very simple interface and supports <a href="https://en.wikipedia.org/wiki/Method_chaining">method chaining</a> — making it possible to generate simple random keys with <em>just one line of code</em>.</blockquote><h3>What you will love about Keygen</h3><p>Most PHP frameworks ship with built-in helpers or libraries to handle random string generation but here are a few reasons and use cases you should consider using the Keygen package:</p><ul><li><strong>Expressive Interface:</strong> <a href="https://en.wikipedia.org/wiki/Method_chaining">Method chaining</a> makes it very easy to generate random keys with just one line of code.</li><li><strong>Saves Time:</strong> You may save yourself some more time trying to <em>reinvent the wheel</em> (implement your own random key generation logic).</li><li><strong>Seamless Key Affixes:</strong> It’s very easy to add a <em>prefix</em> or <em>suffix</em> to the random generated string.</li><li><strong>Key Transformations:</strong> You can process the random generated string through a queue of <a href="https://php.net/manual/en/language.types.callable.php"><em>callables</em></a> before it is finally outputted.</li><li><strong>Key Mutations:</strong> You can control manipulations and mutations of multiple Keygen instances.</li><li><strong>Bulk Key Generation</strong>: The next release (currently on <em>alpha</em>) adds functionality to generate multiple keys at once.</li></ul><p>I will recommend you subscribe to the <a href="https://github.com/gladchinda/keygen-php"><strong>Keygen</strong></a> repository on GitHub to get development updates and know when new releases roll-out. Feel free to bring in your contributions to the project.</p><p><a href="https://github.com/gladchinda/keygen-php">gladchinda/keygen-php</a></p><h3>Getting Started with Keygen</h3><p>Keygen is available on the <a href="https://packagist.org/packages/gladcodes/keygen">Packagist</a> repository and can be installed as a dependency for your project using <a href="https://getcomposer.org/">Composer</a>.</p><pre>composer require gladcodes/keygen</pre><p>If you want to try out the latest development version v1.2.0-alpha , you can install it with the the following command:</p><pre>composer require gladcodes/keygen dev-v1.2.0-alpha</pre><p>Then in your project you can do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bb493b5aeccb645319136df17b3206f/href">https://medium.com/media/7bb493b5aeccb645319136df17b3206f/href</a></iframe><h3><strong>Using Key Affixes and Transformations</strong></h3><p>The Keygen package provides two methods: prefix() and suffix(), for adding affixes to the beginning and/or end of generated keys. Each method takes a string as the first parameter which specifies the affix.</p><p>When affixes are specified in a generator, the length of the generated key includes the string length of the affixes (<em>inclusive affixes</em>). This behaviour can be controlled by passing an optional boolean value as the first parameter of the generate() method. The value truedisables <em>inclusive affixes</em>. If the boolean value is omitted, it defaults to false (enables <em>inclusive affixes</em>). Here is a simple demonstration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b0f39c7c96898b19887c33d9c11ff4e/href">https://medium.com/media/2b0f39c7c96898b19887c33d9c11ff4e/href</a></iframe><p>The Keygen package also allows for one or more transformations to be applied on keys before they are generated. A <em>transformation</em> is simply a <a href="https://php.net/manual/en/language.types.callable.php"><strong>callable</strong></a> that can take the generated key as the first argument and returns a string. Each transformation is executed on the generated key in the same order they are specified before the key is returned. Here is a simple example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0ed8a5a6037a5ae8fb48642a30e8e3c/href">https://medium.com/media/a0ed8a5a6037a5ae8fb48642a30e8e3c/href</a></iframe><h3>Helpful Resources</h3><p>You can get more help on how to use the Keygen package by checking the <a href="https://github.com/gladchinda/keygen-php/wiki/Usage"><strong>Usage Guides</strong></a><strong> </strong>and the <a href="https://github.com/gladchinda/keygen-php/wiki/Documentation"><strong>Documentation</strong></a><strong> </strong>for the current stable release. If you are trying out the latest development version v1.2.0-alpha to experiment with new features like: enhanced expressive syntax, bulk key generations, random length keys, improved key mutations, improved key transformations, etc then you can checkout the <a href="https://github.com/gladchinda/keygen-php/tree/v1.2.0-alpha/docs"><strong>Docs</strong></a> for detailed information.</p><p>For <strong>Laravel</strong> developers, this <a href="https://scotch.io/tutorials/laravel-random-keys-with-keygen"><strong>article</strong></a> will help you get started with using the Keygen package in your Laravel applications.</p><p><a href="https://scotch.io/tutorials/laravel-random-keys-with-keygen">Laravel Random Keys with Keygen</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9037c585ac8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>