<?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 Gilad Dayagi on Medium]]></title>
        <description><![CDATA[Stories by Gilad Dayagi on Medium]]></description>
        <link>https://medium.com/@giladaya_42364?source=rss-54149ee94235------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*idZn_lvQGXxWXgC_7RQivQ.png</url>
            <title>Stories by Gilad Dayagi on Medium</title>
            <link>https://medium.com/@giladaya_42364?source=rss-54149ee94235------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:07:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giladaya_42364/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[Three tools to help you become a better web developer]]></title>
            <link>https://medium.com/@giladaya_42364/three-tools-to-help-you-become-a-better-web-developer-e3c013058679?source=rss-54149ee94235------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3c013058679</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[tools]]></category>
            <dc:creator><![CDATA[Gilad Dayagi]]></dc:creator>
            <pubDate>Sun, 03 Nov 2019 10:02:36 GMT</pubDate>
            <atom:updated>2019-11-18T14:45:37.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZkYDEzDdBD3iSIr_i3d4g.jpeg" /><figcaption>Source: <a href="https://pxhere.com/en/photo/669444">https://pxhere.com/en/photo/669444</a></figcaption></figure><h3>TL;DR</h3><p>Use git, use ESLint, write unit tests.<br>Want to know the reasoning behind each tool? Keep reading!</p><h3>Introduction</h3><p>Whether you are starting out as a developer or already have some experience, improving your coding skills is an ongoing endeavour. But what does it mean to be a better coder?</p><p>While there are many ways to solve a problem with code, some of them are better than others. As Robert Martin wrote:</p><blockquote>Even bad code can function. But if code isn’t clean, it can bring a development organization to its knees.</blockquote><p>Good code doesn’t just work. It is also easy to maintain and reuse. That means that others (or the future you) can understand this code easily, which in turn allows them to solve bugs, add features and refactor it faster and without degrading the whole application.<br>As such, code quality has a big impact on the happiness of everyone involved with the project: engineers, managers, product people and even endusers.</p><p>Being a better coder means writing better code, and getting there requires a lot of practice.</p><p>If you work in a well operated team, this practice usually comes through design and code reviews, but this is not always the case — especially if you are working on small pet projects which are not developed in a team.<br>If that’s the situation, you can use readily available tools that will help you experiment, get feedback and learn better coding practices.</p><h3>Git</h3><figure><img alt="git logo" src="https://cdn-images-1.medium.com/max/200/1*htcG6p5LJys95obqlgFigQ.png" /></figure><p>These days, it’s hard to find software development teams that don’t use some tool for version management of their code. Git is one such tool and is probably the most popular. CVS’s track changes in the code and allows multiple developers to work in parallel and collaborate on the same codebase.</p><p>But what if I’m working alone? what if I’m just playing with some code to learn a new library or try out some ideas? I don’t need no git, right?</p><p>Wrong!</p><p>Small children learn by experimentation. They try out different actions in a safe environment, see the results and then try again something different.<br>The same approach can be applied to coding, and git is the tool that enables that.<br>When used correctly, git enables one to explore different solutions to a problem, try out different libraries, and experiment freely, with the knowledge that at any point in time it is trivial to roll back the changes, get back a good version of the code and start over if needed.<br>It’s like having an ‘undo’ button for entire change sets and is really liberating.</p><p>I recommend to use git for every project — even if it stays local and not uploaded to a remote repository like github.<br>If you already know git it will be trivial and if not you’ll learn a new and important tool.</p><h3>ESLint</h3><figure><img alt="ESLint logo" src="https://cdn-images-1.medium.com/max/200/1*mCuWI4hYRdzKuIR7h1WJpA.png" /></figure><p>Linting tools, like ESLint perform static analysis of the code and recommend on changes that can improve it according to a variety of rules.<br>They are used in software projects to maintain a consistent standard of code style and quality in the project.<br>However, with the right approach they can also help improving one’s coding skills even in personal projects.</p><p>I would divide the ESLint rules to two major categories: code style and best practices. When working in a team it is very important to maintain a standard code style because it makes reading the code easier, but there is no one right code style and this category of rules is less important in the context of this article (I don’t think you’ll be a better coder if you use tabs instead of spaces).</p><p>The second category however, is very relevant for our subject. It include rules that are meant to prevent potential bugs, make the code more readable and thus more maintainable.<br>This is important for development, but if you pay attention these rules can also teach you what patterns to avoid in the future which is a great win. It’s almost like having an experienced developer reviewing every line of your code in real time and giving focused, well explained recommendations for improving your code.</p><p>Starting out with ESLint can be a bit frustrating because there will be many warnings and errors and the reasoning behind each rule is not always clear, but remember that these rules were created by highly experienced developers and were refined over years of usage.<br> Note that the list of rules that are enabled can be customised, so I recommend to start with a strict set of rules and disable a rule only after you understand why it was created and what is the reasoning behind it.</p><p>As a side note I’ll add that even the rules in the “Stylistic Issues” section, which are said to be “quite subjective”, can make your code better (if not prettier).<br>Take for example, the rule max-lines-per-function which limits the number of lines that a function can have. Even though it is considered a styling rule, it has importance beyond just style. This is because a function having too many lines usually indicates that it has too much logic or too many responsibilities and should be broken into smaller, simpler pieces of logic.</p><p>Also note that there are plugins for ESLint which add rules that enforce best practices for more special cases like specific frameworks, functional programming, arrays, promises, etc. and it’s a good idea to get to know them too.</p><h3>Unit Tests</h3><figure><img alt="jest logo" src="https://cdn-images-1.medium.com/max/200/1*a0ZpgymBzkl5JdZ5cOLzzw.png" /></figure><p>Unit tests have a major part in assuring the quality of code in software projects. They help avoid bugs and make refactoring easier.</p><p>But besides that, unit tests can also teach you to write better code. The reason for that is that bad code is usually also hard to test, so as you gain experience writing tests, you will always think about the testability of your code even if you don’t follow a strict Test-Driven-Development workflow. Let’s see two examples for how good testability goes hand-in-hand with good coding practices.</p><p>The first example is global variables.<br>Using global variables is considered a bad practice for various reasons which are not necessarily related to tests. Mainly, they cause the code to be less predictable, less manageable and less reusable as they create implicit, unregulated couplings between different areas of the code base.<br> In the context of unit tests, source code that uses global variables is more difficult to test. The reason is that to be effective, each separate test case has to run in a controlled, well defined setup to consistently produce the expected results. Having global variables around makes it tricky to control the test setup completely as they create implicit dependencies which are hard to control.<br>Because of this difficulty, when you keep unit tests in mind, you will tend to avoid using global variables and get better code.</p><p>For the second example, let’s consider a function with complicated logic and many arguments. Writing good tests for such function is going to be a nightmare, as in order to be effective we must check all execution paths in the function which require as many combinations of input values as possible. Breaking such function down into smaller, simpler functions will make testing easier and at the same time will make the tested code better (= easier to understand and so easier to maintain and reuse).<br>Again — a definite win-win, thanks to the use of unit tests.</p><h3>Summary</h3><p>I hope that I managed to explain the meaning and importance of good code and that you agree that becoming a better coder it is a goal worth pursuing.</p><p>The tools that I introduced above were created for and are used by teams of software developers to enable better collaboration, better standards and better quality.<br>However, as I hopefully demonstrated, these tools also have massive value beyond their mainstream use as aids for self growth and improvement for individual developers and is small projects.<br>These tools, when used wisely allow us to interactively and incrementally learn best practices and produce better code.</p><p>I believe that any software project, even small solo ones should use them.</p><h3>Happy coding!</h3><p><em>If you liked what you read and found it useful — please follow, clap and share!</em></p><p><em>Originally published at </em><a href="https://www.agilesparks.com/blog/three-tools-that-can-help-you-become-a-better-web-developer/"><em>https://www.agilesparks.com</em></a><em> on November 3, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3c013058679" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to go beyond console.log and get the most out of your browser’s debugging console]]></title>
            <link>https://medium.com/free-code-camp/how-to-go-beyond-console-log-and-get-the-most-out-of-your-browsers-debugging-console-e185256a1115?source=rss-54149ee94235------2</link>
            <guid isPermaLink="false">https://medium.com/p/e185256a1115</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[console]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Gilad Dayagi]]></dc:creator>
            <pubDate>Tue, 17 Jul 2018 14:42:52 GMT</pubDate>
            <atom:updated>2018-07-17T14:42:52.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lvtq6fDOejQmexdK5t2Npw.png" /><figcaption>An old console</figcaption></figure><p>The console object is a very useful feature of browsers that has been around for many years. It provides access to the browser’s debugging console.<br>Most web developers know how to print messages to the console using console.log. But I’ve found that many don’t know about other features of the console, even though they can be very useful for every web developer.</p><p>In this post, I’ll go over some of these lesser known features and capabilities. I hope that you will find them useful and interesting, and will incorporate them into your day to day workflow and code.</p><p>I added a screenshot of the result of each example. If you want to try things for yourself, just open the DevTools and copy-paste the examples.</p><h3>Using multiple arguments</h3><p>It is quite common to log several values together. These may be a message along with a related value or the content of several related variables.</p><p>Here are two ways I’ve seen developers achieve this:</p><h4>1. String concatenation</h4><pre>const a = 123;<br>const b = &#39;abc&#39;;<br>const c = {aa: 234, bb: 345};<br>console.log(&#39;Foo bar &#39; + a + &#39; &#39; + b + &#39; &#39; + c);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*dMD1uarjUFDDK6r95zaKsg.png" /><figcaption>Result of string concatenation</figcaption></figure><h4>2. Using multiple calls</h4><pre>const a = 123;<br>const b = &#39;abc&#39;;<br>const c = {aa: 234, bb: 345};<br>console.log(&#39;Foo bar&#39;);<br>console.log(a);<br>console.log(b);<br>console.log(c);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*1zYLgoDoxwaX-24rofNz7A.png" /><figcaption>Result of multiple calls</figcaption></figure><p>These methods may work (sort of), but:</p><ul><li>They are not flexible</li><li>They are not very readable</li><li>They are cumbersome to write</li><li>They need special means to work properly with object variables</li></ul><p>There are several better alternatives for outputting many variables. The most useful one for quick data dump is sending multiple arguments to console.log, like so:</p><pre>const a = 123;<br>const b = &#39;abc&#39;;<br>const c = {aa: 234, bb: 345};<br>console.log(&#39;Foo bar&#39;, a, b, c);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*WbwwXG1TSuT2ep7RjppmGA.png" /><figcaption>Result of multiple arguments</figcaption></figure><p>This is very handy for debugging, but the output is not very controllable. For output that is intended to be read (like for a library), I would use a different method, which we’ll get to later on.</p><h3>Using different log levels</h3><p>Besides the familiar console.log, there are other logging methods that correspond to different log levels:</p><pre>console.debug(&#39;Debug message&#39;);<br>console.info(&#39;Info message&#39;);<br>console.log(&#39;Good old log message&#39;);<br>console.warn(&#39;A warning message&#39;);<br>console.error(&#39;This is an error&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*6JwjQe6JOw_SYdxVFDTigw.png" /><figcaption>Log levels as seen in Google Chrome</figcaption></figure><p>Each log level may have a different default style, which makes spotting errors and warnings at a glance easier.</p><p>You can usually also filter which log levels you want to be visible in the DevTools console. This may help reduce clutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*52re_00cjLR5oTSe36yVbw.png" /><figcaption>Filtering log levels in Google Chrome</figcaption></figure><p>The appearance of the different levels and the filtering granularity changes from browser to browser.</p><h3>Grouping console lines</h3><p>Some times it is useful to group log messages together. It may allow for more organised and readable output.</p><p>This is actually very simple to achieve:</p><pre>console.group();<br>console.log(&#39;First message&#39;);<br>console.log(&#39;Second message&#39;);<br>console.groupEnd();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*IQ32s8I9ntNe1iZB93_23Q.png" /><figcaption>Grouped log messages</figcaption></figure><p>Note that log groups can also be nested and labeled:</p><pre>console.group(&#39;Group aaa&#39;);<br>console.log(&#39;First message&#39;);<br>console.group(&#39;Group bbb&#39;);<br>console.log(&#39;level 2 message a&#39;);<br>console.log(&#39;Level 2 message b&#39;);<br>console.groupEnd();<br>console.log(&#39;Second message&#39;);<br>console.groupEnd();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*qw1YcnKao6ChrkM-qE7CoA.png" /><figcaption>Nested and labeled groups</figcaption></figure><p>In case you want the group to appear collapsed, use console.groupCollapsed()</p><h3>Measuring performance</h3><p>Measuring the time between points in the code can serve as a quick way to check the performance of some operations.</p><p>Here is a trivial way to do this:</p><pre>const start = Date.now();<br>// do some stuff<br>console.log(&#39;Took &#39; + (Date.now() - start) + &#39; millis&#39;);</pre><p>This works, but there’s a more elegant way to achieve something similar:</p><pre>console.time(&#39;Label 1&#39;);<br>// do some stuff<br>console.timeEnd(&#39;Label 1&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*sUmSjg7OWt5HGlamNFhmdg.png" /><figcaption>Measuring time with the console</figcaption></figure><p>The code is shorter, the measurement is more accurate, and you can keep track of up to 10,000 different timers in parallel on a page.</p><h3>String substitution</h3><p>Previously we learned that you can pass multiple arguments to console.log to output multiple values simultaneously. Another way to achieve something similar is to use string substitution. This method requires familiarity with the available placeholders, but offers greater control over the output.</p><pre>const a = 123;<br>const b = &#39;abc&#39;;<br>const c = {aa: 234, bb: 345};<br>console.log(&#39;number %d string %s object %o&#39;, a, b, c);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*j-H_WuCb21c8rP7eh5HUEQ.png" /><figcaption>Logging with string substitution</figcaption></figure><p>Take a look at the documentation (link in the end) for a list of available placeholders.</p><h3>Styling</h3><p>It can be nice to style different log messages differently to increase readability.</p><p>We already mentioned that browsers give different default styling to some log levels, but this can also be customized according to your specific needs. Styling is done using a subset of CSS rules, passed in a string as the second parameter, and applied using the marker %c.</p><p>Note that you can have different styles for different parts of the log message.</p><p>For example:</p><pre>console.log(&quot;Normal %cStyled %clorem %cipsum&quot;, &quot;color: blue; font-weight: bold&quot;, &quot;color: red&quot;, &quot;background-image: linear-gradient(red, blue); color: white; padding: 5px;&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*Hu2G8alpCzkTNIUqH9cxTA.png" /><figcaption>Styled log messages</figcaption></figure><h3>Summary</h3><p>In this post we have seen some of the features of console that I think are less well-known and more useful. This is by no means an exhaustive list of everything the console can do, as it has many more tricks up its sleeve.</p><p>If this got you interested and you want to find out what other things you can do with the console, I recommend reading the <a href="https://developer.mozilla.org/en-US/docs/Web/API/console">relevant documentation on MDN</a> and trying things out in DevTools.</p><p><em>If you found this useful please give me some claps so more people can see this. <br>You can also follow me here or on twitter (@giladaya )<br>Thanks for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e185256a1115" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-go-beyond-console-log-and-get-the-most-out-of-your-browsers-debugging-console-e185256a1115">How to go beyond console.log and get the most out of your browser’s debugging console</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[Get Sheet Done — using Google Spreadsheets as your data backend]]></title>
            <link>https://medium.com/free-code-camp/get-sheet-done-using-google-spreadsheets-as-your-data-backend-650ba23dc6d9?source=rss-54149ee94235------2</link>
            <guid isPermaLink="false">https://medium.com/p/650ba23dc6d9</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Gilad Dayagi]]></dc:creator>
            <pubDate>Mon, 21 Aug 2017 16:03:16 GMT</pubDate>
            <atom:updated>2017-08-23T05:39:20.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulO04x_24taM1kWjlBHW7w.jpeg" /></figure><p>If you want to rapidly prototype your next web apps, try using Google Spreadsheets as your data backend.</p><p>With a small library I created called <a href="https://www.npmjs.com/package/get-sheet-done">get-sheet-done</a>, you can have a free cloud database with GUI editor up and running in less than 5 minutes.</p><h3>The story behind Get Sheet Done</h3><p>A while back, I needed to quickly prototype a web app that could display structured data. The catch was that these data had to be frequently edited by a non-technical person.</p><p>Since this was a prototype, I was looking for a solution that would give me the most bang for the buck, when taking into account development time and maintenance costs.</p><p>I considered several solutions, including using a full backend-as-a-service approach that stored the data as a file in Dropbox. Then I chose a somewhat non-orthodox solution: I stored the data in a Google spreadsheet.</p><h3>When is a spreadsheet-based database a suitable solution?</h3><p>Using Google spreadsheets as a database for web applications in not a mainstream solution, and it may or may not be suitable for your next project.</p><p>To help you decide whether this is a good option, I’ve put together the following list of considerations.</p><p>Remember: we’re talking about a spreadsheet, which works great for structured, tabular data. But doesn’t work well for a document / object store.</p><p>Other than that, here are some pros and cons to consider:</p><h4>Pros</h4><ul><li>It’s free</li><li>Very easy to set up — no need for API keys or complicated SDKs</li><li>Zero maintenance</li><li>You get a data editing GUI for free</li><li>You get write access management for free</li><li>Can include internal calculations using spreadsheet functions</li><li>The app that uses the data can be easily upgraded in a later phase to use a real database, as data is exposed as standard JSON</li><li>Some level of automation can be achieved by using apps-scripts in combination with <a href="https://developers.google.com/apps-script/guides/sheets#triggers">time-driven triggers</a></li><li>It can be combined with Google Forms for data collection</li></ul><h4>Cons</h4><ul><li>No server-side filtering logic to talk about</li><li>All the data you want to access has to be publicly accessible</li><li>The entire database is manually-editable, so a human error may break the application. For example, if someone accidentally changes the label of some field, it won’t be available for the application.<br>This can be partially remedied by protecting the critical cells</li><li>You can have <a href="https://support.google.com/drive/answer/37603?hl=en">up to 2 million cells</a> in a spreadsheet</li></ul><h3>How I implemented this</h3><p>I couldn’t find a lot of information nor good libraries for easily reading data from a Google spreadsheet. So I decided to roll my own solution. It is now available on npm as the <a href="https://www.npmjs.com/package/get-sheet-done">get-sheet-done package</a>.</p><p>My implementation is based on the fact that once a spreadsheet is published to the web, it’s also available as a standard RSS feed, which can be fetched and parsed.</p><p>One complication is you have to fetch it using JSONP or somehow handle CORS. I chose to go with JSONP and use the <a href="https://www.npmjs.com/package/fetch-jsonp">fetch-jsonp</a> library to manage this, so there’s no need for special measures.</p><h3>How to use it</h3><p>Here’s what you need to do to get a simple editable database for your web app:</p><ol><li>Create a google spreadsheet with some data</li><li>Publish the sheet to the web: File -&gt; Publish to the web.<br>Note the document ID from the URL</li><li>Install the package: npm install --save get-sheet-done</li><li>Get the data:</li></ol><pre>import <strong>GetSheetDone </strong>from &#39;get-sheet-done&#39;</pre><pre><strong>GetSheetDone</strong>.labeledCols(DOCUMENT_ID).then(sheet =&gt; console.log(sheet))</pre><p>5. Profit!</p><p>Note that there are three functions you can use to fetch the data, depending on how it should be parsed: raw 2d array, array of objects, object of objects.</p><p>Here’s a <a href="https://giladaya.github.io/get-sheet-done/">live demo</a> you can play with.</p><p>It’s worth considering using Google Spreadsheets as a data source for a web application, especially if you’re just building a quick prototype. It has some unique advantages, and implementation is easy with (or without) my library.</p><p>Let me know in the comments if you found this library useful and whether there are missing features.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=650ba23dc6d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/get-sheet-done-using-google-spreadsheets-as-your-data-backend-650ba23dc6d9">Get Sheet Done — using Google Spreadsheets as your data backend</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[How to dump the for loop and stay alive]]></title>
            <link>https://codeburst.io/how-to-dump-the-for-loop-and-stay-alive-ef67ff91cfd0?source=rss-54149ee94235------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef67ff91cfd0</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[loop]]></category>
            <dc:creator><![CDATA[Gilad Dayagi]]></dc:creator>
            <pubDate>Sat, 08 Jul 2017 00:22:06 GMT</pubDate>
            <atom:updated>2017-07-08T00:22:06.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNZ-zIjacjfXJFOzKPloYQ.png" /></figure><p>The classic for loop is a widely used feature of javascript programs. It can be used for running any piece of code multiple times, and it used to be what was used for implementing operations on arrays.</p><p>A typical for loop would look something like this:</p><pre>var arr = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;];<br>for (var i = 0; i &lt; arr.length; i++) {<br>  console.log(arr[i]);<br>}</pre><p>It gets the job done, but nowadays there are alternatives that may be more suitable for operating on arrays, which I’ll refer to as array functions.</p><p>These functions, like map, reduce and filter are part of the Array prototype. Some of them have been around for some time and have great browser support (down to IE9). <br>Some newer array functions like find became standard as part of ES2015 so have less support, but can be very handy. <br>Depending on your project requirement and setup, you may still want to use them.</p><p>So, why would you want to use array functions instead of the good old for loop?</p><p>There are several reasons:</p><ul><li>Usually it results in shorter, more readable code</li><li>You don’t have to define some temporary helper variables (like i above)</li><li>Array elements are directly available for processing and you don’t have to access them using the index</li><li>The array functions are more expressive and convey better what the code does compared with the generic for keyword</li><li>The new functions are not prone to ‘<a href="https://en.wikipedia.org/wiki/Off-by-one_error">off by one</a>’ bugs</li><li>If you are into functional programming, using loops is discouraged (to put it mildly)</li></ul><p>Now I wan’t deny that the classic for loop does have some benefits:</p><ul><li>It is very flexible</li><li>It’s supported everywhere javascript runs</li><li>It has better performance than the specialized array functions</li></ul><p>In most cases however, the benefits of array functions win over those of the for loop and should be used.</p><p>If you want to start using array functions, read on to see a couple of examples for common array operations that implement the same logic using both for and the newer functions.</p><h4>The example array</h4><p>All the following examples will assume that this array is defined and available in the scope:</p><pre>var people = [{<br>  id: 1,  <br>  name: &#39;Alice&#39;,<br>  age: 16<br>},<br>{<br>  id: 2,<br>  name: &#39;Bob&#39;,<br>  age: 19<br>},<br>{<br>  id: 3,<br>  name: &#39;Carol&#39;,<br>  age: 15<br>},<br>{<br>  id: 4,<br>  name: &#39;David&#39;,<br>  age: 21<br>}];</pre><h4>Sum an array</h4><p>Let’s find the sum of the ages of the people in our array. This can be useful for calculating the average age for example.</p><p>Using for:</p><pre>var sum = 0;</pre><pre>for (var i = 0; i &lt; people.length; i++) {<br>  sum += people[i].age;<br>}</pre><p>Using Array.reduce:</p><pre>const sum = people.reduce(function(acc, person){<br>  return acc + person.age;<br>}, 0)</pre><p>If we combine reduce with the ES6 arrow functions, we can get even shorter, more focused code.</p><p>Using Array.reduce + arrow functions:</p><pre>const sum = people.reduce((acc, person) =&gt; (acc + person.age), 0);</pre><h4>Interlude: a note about arrow functions</h4><p>Arrow functions are part of the ES2015 standard and are really cool, so I’ll be using them in the rest of the examples - they work very well with array functions.</p><p>If you are not familiar with arrow functions, know that they are <a href="http://caniuse.com/#feat=arrow-functions">natively supported in all modern browsers but not in IE</a> and you can read a nice intro on using them in <a href="https://codeburst.io/javascript-arrow-functions-for-beginners-926947fc0cdc">this article</a>.</p><p>If you are still uncomfortable using arrow functions, it’s usually trivial to replace them in the examples with regular javascript functions.</p><h4>Filter an array</h4><p>Let’s say we want an array with just the records for adults.</p><p>Using for:</p><pre>var adults = [];</pre><pre>for (var i = 0; i &lt; people.length; i++) {<br>  if (people[i].age &gt; 16) {<br>    adults.push(people[i]);<br>  }<br>}</pre><p>Using Array.filter:</p><pre>const adults = people.filter(person =&gt; person.age &gt; 16);</pre><h4>Find the element with max property</h4><p>Say we want to find the record of the oldest person in our array.</p><p>Using for:</p><pre>var oldest = {age: 0};</pre><pre>for (var i = 0; i &lt; people.length; i++) {<br>  if (people[i].age &gt; oldest.age) {<br>    oldest = people[i];<br>  }<br>}</pre><p>Using Array.reduce:</p><pre>const oldest = people.reduce((acc, person) =&gt; <br>  person.age &gt; acc.age ? person : acc<br>);</pre><h4>Extract a property from an array of objects</h4><p>Say we need an array with just the names, let’s see how to create it.</p><p>Using for:</p><pre>var names = [];</pre><pre>for (var i = 0; i &lt; people.length; i++) {<br>  names.push(people[i].name);<br>}</pre><p>Using Array.map:</p><pre>const names = people.map(val =&gt; val.name);</pre><h4>Index an array of objects</h4><p>Sometimes it’s beneficial to index an array of objects by one of the properties in the objects. For example, you might want to index the array by an ID property so you could more efficiently look up objects in the array.</p><p>Continuing with the example array, Let’s see how to do that:</p><p>Using for:</p><pre>var iPeople = {};</pre><pre>for (var i = 0; i &lt; people.length; i++) {<br>  iPeople[people[i].id] = people[i];<br>}</pre><p>Using Array.reduce:</p><pre>const iPeople = people.reduce((acc, person) =&gt; {<br>  acc[person.id] = person;<br>  return acc;<br>}, {});</pre><h4>Find an element in array</h4><p>Say we want to find the first record for a given name.</p><p>Using for:</p><pre>var details = null;</pre><pre>for (var i = 0; i &lt; people.length; i++) {<br>  if (people[i].name === &#39;Bob&#39;){<br>    details = people[i];<br>    break;<br>  }<br>}</pre><p>Using Array.find:</p><pre>const details = people.find(val =&gt; val.name === &#39;Bob&#39;);</pre><p>Note that find is not supported in IE but is natively supported in all modern browsers and there’s a <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find#Pollyfill">polyfill</a>.</p><h4>Summary</h4><p>As you can see from the examples above, the new array functions are very useful, easy to work with and result in shorter, more readable code.</p><p>There are more array functions which were not demonstrated here, but if you are interested, they are very well documented on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods_2">MDN</a>.</p><p>Most of the array functions in this article are natively supported in all modern browsers all the way down to IE9. One exception is Array.find which is only supported from Edge 12</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef67ff91cfd0" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/how-to-dump-the-for-loop-and-stay-alive-ef67ff91cfd0">How to dump the for loop and stay alive</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[Promises for the (Web) Worker]]></title>
            <link>https://codeburst.io/promises-for-the-web-worker-9311b7831733?source=rss-54149ee94235------2</link>
            <guid isPermaLink="false">https://medium.com/p/9311b7831733</guid>
            <category><![CDATA[es2015]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Gilad Dayagi]]></dc:creator>
            <pubDate>Mon, 03 Jul 2017 13:59:53 GMT</pubDate>
            <atom:updated>2017-07-03T13:59:53.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2h5IScOuuzxvuQMmtXCIHA.jpeg" /></figure><p>While working on the <a href="https://github.com/giladaya/barcode-detector-polyfill">Barcode Detector Polyfill</a>, I needed to wrap a web worker with a promise based API.</p><p>The use of a promise in this case was dictated by the standard proposal, and the use of a web worker was needed because of the heavy calculations that the detector requires.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Web workers</a> have been introduced about 8 years ago so they are really not new, but they are mature and <a href="http://caniuse.com/webworkers/embed/">very well supported</a>.</p><p>In a nutshell, web workers allow to run code in a separate processing thread, so lengthy computations won’t block the main thread. This is important because when the main thread is blocked, the web app will be unresponsive.</p><p>As browsers become more powerful, they need to handle more computational tasks, so using web workers makes sense in more cases.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">Promises</a> as a concept have also been around for several years, and have been standardized as part of ES6 (ES2015). They are <a href="http://caniuse.com/promises/embed/">supported</a> in all modern browsers and there are good <a href="https://github.com/stefanpenner/es6-promise">polyfills</a> for older ones.</p><p>In two words, they allow to write asynchronous code in more synchronous way, making it more readable and maintainable.</p><p>So, how can we combine these two technologies?</p><h4>The challenge</h4><p>As web workers run in a separate thread, they need some way to communicate with the main thread. This is done by exchanging messages which can contain arbitrary data and are sent and received asynchronously between the main and worker threads. By default, these messages don’t have any context other than their content.</p><p>Now in our case, if a web worker computation was initiated inside a promise, we want that same promise to be resolved (or rejected) when that specific computation is complete and the result is available.</p><p>The way to achieve this, is with some book keeping. A wrapper around the web worker will remember which callback functions belong to which computation and will call the right callback function upon getting a response message.</p><p>This is simpler than it sounds, and easier to explain with an example.</p><h4>Code Example</h4><p>In the code below I’ll be using ES2015 syntax and features. <br>A complete, live example can be found <a href="https://www.webpackbin.com/bins/-Klnr00bTOLrtj0oVza2">here</a>.</p><p><strong>Wrapper.js:</strong></p><pre>const resolves = {}<br>const rejects = {}<br>let globalMsgId = 0</pre><pre>// <em>Activate calculation in the worker, returning a promise</em><br>function <strong>sendMsg</strong>(payload, worker){<br>  const msgId = globalMsgId++<br>  const msg = {<br>    id: msgId,<br>    payload<br>  }</pre><pre>  return new <strong>Promise</strong>(function (resolve, reject) {<br>    // <em>save callbacks for later</em><br>    resolves[msgId] = resolve<br>    rejects[msgId] = reject</pre><pre>    worker.postMessage(msg)<br>  }) <br>}</pre><pre>// <em>Handle incoming calculation result</em><br>function <strong>handleMsg</strong>(msg) {<br>  const {id, err, payload} = msg.data</pre><pre>  if (payload) {<br>    const resolve = resolves[id]<br>    if (resolve) {<br>      resolve(payload)<br>    }<br>  } else {<br>    // <em>error condition</em><br>    const reject = rejects[id]<br>    if (reject) {<br>        if (err) {<br>          reject(err)<br>        } else {<br>          reject(&#39;Got nothing&#39;)<br>        }<br>    }<br>  }<br>  <br>  // <em>purge used callbacks</em><br>  delete resolves[id]<br>  delete rejects[id]<br>}</pre><pre>// <em>Wrapper class</em><br>class <strong>Wrapper</strong> {<br>  constructor() {<br>    this.worker = new Worker(&#39;./worker.js&#39;)<br>    this.worker.onmessage = handleMsg<br>  }<br>  <br>  oche(str) {<br>    return sendMsg(str, this.worker)<br>  }<br>}</pre><pre>export default <strong>Wrapper</strong></pre><p>The wrapper needs to do most of the bookkeeping.</p><p>When the process function oche is called, a new promise is returned, but before that we do 3 things (see sendMsg in the code):</p><ol><li>Define a unique ID for this call</li><li>Store the resolve and reject callback functions of the promise</li><li>Send a message to the worker with the input data for the computation along with the unique message ID.</li></ol><p>In the handler for incoming messages from the worker (see handleMsg in the code), we also have 3 main steps:</p><ol><li>Fetch the callback functions that we stored using the incoming message unique ID</li><li>Call the relevant callback function, thus resolving or rejecting the original promise</li><li>Do some cleanup by deleting the stored callback functions for this message, as we don’t need them anymore.</li></ol><p><strong>worker.js:</strong></p><pre>// <em>Simulate lengthy calculation or an async call</em><br>function <strong>doCalculation</strong>(data, cb) {<br>  let result = null, err = null<br>  <br>  if (typeof data === &#39;string&#39;) {<br>    result = data.split(&#39;&#39;).reverse().join(&#39;&#39;)<br>  } else {<br>    err = &#39;Not a string&#39;<br>  }</pre><pre>  const delay = Math.ceil(Math.random() * 1000)<br>  setTimeout(function() {<br>    cb(err, result)<br>  }, delay)<br>}</pre><pre>// <em>Handle incoming messages</em><br>self.<strong>onmessage</strong> = function(msg) {<br>  const {id, payload} = msg.data<br>  <br>  doCalculation(payload, function(err, result) {<br>    const msg = {<br>      id,<br>      err,<br>      payload: result<br>    }<br>    self.postMessage(msg)<br>  })<br>}</pre><p>The worker can do whatever it needs with the messages it receives. It has just two requirements:</p><ol><li>Reply with exactly one outgoing message for each incoming message.</li><li>Include the ID from the incoming message in the outgoing message, together with any result data.</li></ol><p><strong>index.js:</strong></p><pre>import <strong>Wrapper</strong> from &#39;./Wrapper&#39;<br>const wrapper = new <strong>Wrapper</strong>()</pre><pre>console.log(&#39;Calling&#39;)</pre><pre>wrapper.oche(&#39;hello world&#39;).then(<br>  (res) =&gt; console.log(&#39;Got result: &#39; + res)<br>).catch(<br>  (err) =&gt; console.log(&#39;Got error: &#39; + err)<br>)</pre><p>Using the wrapper is just standard promise use. Everything worker related is encapsulated and handled by the wrapper, so we don’t need anything special on this side.</p><h4>Final notes</h4><p>The above example is pretty basic and was meant to convey the main idea. <br>Of course it can be extended as needed, for example:</p><ul><li>The wrapper and worker can be made to support more processing actions using a similar pattern</li><li>The wrapper can be made more robust by keeping a timer for each call which will prevent the callback stores from filling with zombie entries in cases the worker does not reply for some reason.</li></ul><p>Also, while I think that this pattern is pretty straight-forward and easy to implement, if you prefer something ready-made, there’s a <a href="https://github.com/nolanlawson/promise-worker">library available</a> that implements it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9311b7831733" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/promises-for-the-web-worker-9311b7831733">Promises for the (Web) Worker</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 create visual variants for React components using styled-components]]></title>
            <link>https://medium.com/free-code-camp/visual-variants-for-react-components-with-styled-components-dfaff6a76273?source=rss-54149ee94235------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfaff6a76273</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Gilad Dayagi]]></dc:creator>
            <pubDate>Mon, 22 May 2017 18:36:27 GMT</pubDate>
            <atom:updated>2017-07-25T17:01:15.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NAdLxbM-7qOVjUYOhVwNGg.jpeg" /></figure><p><a href="https://styled-components.com/">Styled-components</a> is a library for styling React components that took the React world by storm when it was introduced at the end of 2016. The library is powerful and flexible. And solves most of the <a href="https://speakerdeck.com/vjeux/react-css-in-js">problems that classic CSS has</a> in the so-called Component Age.</p><p>In this post, I’ll look into one aspect of styling components:</p><p>How to implement a component that can have multiple visual variants.</p><p>And I’ll show you three different ways to achieve this using styled-components, which I call:</p><p><strong>1: The Classic Approach</strong></p><p><strong>2: The Component Approach</strong></p><p><strong>3: The Extending Approach</strong></p><p>I’ll assume some knowledge of React and styled-components. But in case you need a reference, both have excellent documentation. You can find React’s docs <a href="https://facebook.github.io/react/docs/hello-world.html">here</a> and styled-component’s <a href="https://www.styled-components.com/docs/">here</a>.</p><p>You can see a live demo of each approach <a href="https://www.webpackbin.com/bins/-KkNC0RNPi5Lywsh4Ry6">here</a>.</p><h3>Visual variants</h3><p>In React, a component translates state and props into a visual representation. This usually means into a DOM element.</p><p>And sometimes you need a component to switch between several visual states, depending on certain conditions. Meaning you need the component to change, perhaps, color to convey different information. For example:</p><ul><li>A button can be normal, primary, secondary, disabled, etc.</li><li>A list item can be selected or not selected.</li><li>A form element can be required, with error or normal.</li></ul><p>A good example of this visual variant pattern is <a href="http://getbootstrap.com/css/#buttons">Bootstrap’s button styles</a>. You style the button independent of its content and choose among a host of variants. And each variant of the button serves its own semantic purpose (like success or disabled) as opposed to appearance (like blue, round, etc.).</p><p>So how do you implement visual variants with styled-components? You can do so using the Classic Approach, Component Approach, or Extending Approach.</p><h4>#1: The Classic Approach</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*hIo0XmtmY5j7HL4niYaZ5A.png" /><figcaption>Results using the Classic Approach</figcaption></figure><p>Styled-components fully supports CSS. Which includes the ability to apply style rules to “subclasses” of elements. That means you can create visual variants using CSS classes not so different from how it’s done with plain CSS.</p><p>To select a variant of a component you modify the className prop. You can also pass a number of classes this way and combine several variants, say, ‘primary’ and ‘large’.</p><p><strong>Example</strong></p><pre>// <em>ButtonClassic.jsx</em><br>import styled from &#39;styled-components&#39;</pre><pre>const <strong>ButtonClassic</strong> = styled.button`<br>  background: #fff;<br>  color: #333;<br>  font-size: 1em;<br>  margin: 1em;<br>  padding: 6px 12px;<br>  border: 1px solid #ccc;<br>  border-radius: 4px;<br>  cursor: pointer;</pre><pre><em>/* Style sub-classes */</em><br>  &amp;.primary {<br>    color: #fff;<br>    background: #337ab7;<br>    border-color: #2e6da4;<br>  }<br>  &amp;.success {<br>    color: #fff;<br>    background-color: #5cb85c;<br>    border-color: #4cae4c;<br>  }<br>  &amp;.link {<br>    color: #337ab7;<br>    background-color: transparent;<br>    border: none;<br>    border-radius: 0;<br>    font-weight: 400;<br>  }<br>  &amp;.large {<br>    font-size: 1.2em;<br>    padding: 10px 16px;<br>    border-radius: 6px;<br>  }<br>  &amp;.disabled {<br>    color: #ddd;<br>    background-color: #aaa;<br>    border: 1px solid #aaa;<br>  }<br>`;</pre><pre>export default <strong>ButtonClassic</strong></pre><p><strong>Usage</strong></p><pre>// ... <br>&lt;<strong>ButtonClassic</strong>&gt;Default&lt;/<strong>ButtonClassic</strong>&gt;<br>&lt;<strong>ButtonClassic</strong> className=&quot;primary&quot;&gt;Primary&lt;/<strong>ButtonClassic</strong>&gt;<br>&lt;<strong>ButtonClassic</strong> className=&quot;success&quot;&gt;Success&lt;/<strong>ButtonClassic</strong>&gt;<br>&lt;<strong>ButtonClassic</strong> className=&quot;link&quot;&gt;Link&lt;/<strong>ButtonClassic</strong>&gt;</pre><pre>// <em>With Combos</em><br>&lt;<strong>ButtonClassic</strong> className=&quot;primary large&quot;&gt;<br>  Primary Large<br>&lt;/<strong>ButtonClassic</strong>&gt;</pre><pre>&lt;<strong>ButtonClassic</strong> className=&quot;disabled primary large&quot;&gt;<br>  Primary Large Disabled<br>&lt;/<strong>ButtonClassic</strong>&gt;</pre><p><strong>Pros</strong></p><ul><li>Easy to support several variants.</li><li>Easy to combine a list of variants (for example, primary + large + disabled)</li><li>Code is readable and compact</li><li>Easy to port styles from plain CSS</li></ul><p><strong>Cons</strong></p><ul><li>Doesn’t use standard component facilities (props)</li><li>When combining classes, results depend on the declaration order of the style rule. Like in classic CSS. This may lead to unexpected behavior.</li></ul><h4>#2: The Component Approach</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*29X6lxVLo7KuFhutOWrC3g.png" /><figcaption>Results using the Component Approach</figcaption></figure><p>Styled components, like their name suggest are simply normal components. Which means they can receive props. Props that can be accessed in the style declaration and used to determine values for style rules.</p><p>I call this the Component Approach because it works like how usual React components work. Where prop values are used to calculate the visual representation of the component. In this case, the concept is limited to styling, rather than content.</p><p><strong>Example</strong></p><pre>// <em>ButtonComponent.jsx</em> <br>import styled from &#39;styled-components&#39;</pre><pre>const <strong>ButtonComponent</strong> = styled.button`<br>  background: ${props =&gt; props.primary ? &#39;#337ab7&#39; : &#39;#fff&#39;};<br>  color: ${props =&gt; props.primary ? &#39;#fff&#39; : &#39;#333&#39;};<br>  font-size: 1em;<br>  margin: 1em;<br>  padding: 6px 12px;<br>  border: ${props =&gt; props.primary ? &#39;1px solid #2e6da4&#39; : &#39;1px solid #ccc&#39;};<br>  border-radius: 4px;<br>  cursor: pointer;<br>`</pre><pre>export default <strong>ButtonComponent</strong></pre><p><strong>Usage</strong></p><pre>// ...<br>&lt;<strong>ButtonComponent</strong>&gt;Default&lt;/<strong>ButtonComponent</strong>&gt;<br>&lt;<strong>ButtonComponent</strong> primary={true}&gt;Primary&lt;/<strong>ButtonComponent</strong>&gt;</pre><p><strong>Pros</strong></p><ul><li>Standard React component behavior, deriving visual representation from props</li></ul><p><strong>Cons</strong></p><ul><li>If more than two states are needed, the code can become unreadable</li><li>There is some code repetition, especially if many rules differ between variants.</li></ul><h4>#3: The Extending Approach</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*iC0xQF31knoMBh8n-1S48A.png" /><figcaption>Results using the extend way</figcaption></figure><p>Besides primitive elements, styled-components allows us to also style custom components. So you can re-style a base or default component. And override relevant style rules to create a visual variant.</p><p><strong>Example</strong></p><pre>// <em>ButtonExtend.jsx</em><br>import styled from &#39;styled-components&#39;</pre><pre>const <strong>ButtonExtend</strong> = styled.button`<br>  background: #fff;<br>  color: #333;<br>  font-size: 1em;<br>  margin: 1em;<br>  padding: 6px 12px;<br>  border: 1px solid #ccc;<br>  border-radius: 4px;<br>  cursor: pointer;<br>`</pre><pre>export default <strong>ButtonExtend</strong></pre><pre>export const <strong>ButtonExtendPrimary</strong> = styled(ButtonExtend)`<br>  color: #fff;<br>  background: #337ab7;<br>  border-color: #2e6da4;<br>`</pre><pre>export const <strong>ButtonExtendSuccess</strong> = styled(ButtonExtend)`<br>  color: #fff;<br>  background-color: #5cb85c;<br>  border-color: #4cae4c;<br>`</pre><pre>export const <strong>ButtonExtendLink</strong> = styled(ButtonExtend)`<br>  color: #337ab7;<br>  background-color: transparent;<br>  border: none;<br>  border-radius: 0;<br>  font-weight: 400;<br>`</pre><p><strong>Usage</strong></p><pre>// ...<br>&lt;<strong>ButtonExtend</strong>&gt;Default&lt;/<strong>ButtonExtend</strong>&gt;<br>&lt;<strong>ButtonExtendPrimary</strong>&gt;Primary&lt;/<strong>ButtonExtendPrimary</strong>&gt;<br>&lt;<strong>ButtonExtendSuccess</strong>&gt;Success&lt;/<strong>ButtonExtendSuccess</strong>&gt;<br>&lt;<strong>ButtonExtendLink</strong>&gt;Link&lt;/<strong>ButtonExtendLink</strong>&gt;</pre><p><strong>Pros</strong></p><ul><li>Each variant is a separate component</li><li>Easy to have many variants</li><li>Code is very readable</li></ul><p><strong>Cons</strong></p><ul><li>To get a different variant, a different component needs to be rendered vs changing a property on the same component which might be more cumbersome.</li><li>Can’t easily support combining multiple variants.</li></ul><h3>Summary</h3><p>I have listed all the ways for doing visual variants that I had a chance to try, but there might be others. Which approach is best depends on your specific needs and preferences.</p><p>If you missed the link above, a live demo of the code examples is available in this <a href="https://www.webpackbin.com/bins/-KkNC0RNPi5Lywsh4Ry6">webpack bin</a>.</p><p>If you know of other approaches using styled-components, let me know in the comments below.</p><p><strong>Update (Jun 9 2017)</strong></p><p>Styled-components V2 was <a href="https://medium.com/styled-components/announcing-v2-f01ef3766ac2">released a few days ago</a> with a slightly better way to use the Extending Approach.</p><p>There is now a specific function for this approach named <a href="https://www.styled-components.com/docs/basics#extending-styles">extend</a>. The function is like the original method, but under the hood creates a new stylesheet by extending the old one. And thus doesn’t generate two classes.</p><p>So the original example for the Extending Approach, would look something like this:</p><pre>// <em>ButtonExtendV2.jsx</em><br>import styled from &#39;styled-components&#39;</pre><pre>const <strong>ButtonExtendV2</strong> = styled.button`<br>  background: #fff;<br>  color: #333;<br>  font-size: 1em;<br>  margin: 1em;<br>  padding: 6px 12px;<br>  border: 1px solid #ccc;<br>  border-radius: 4px;<br>  cursor: pointer;<br>`</pre><pre>export default <strong>ButtonExtendV2</strong></pre><pre>export const <strong>ButtonExtendV2Primary</strong> = ButtonExtendV2.extend`<br>  color: #fff;<br>  background: #337ab7;<br>  border-color: #2e6da4;<br>`</pre><pre>export const <strong>ButtonExtendV2Success</strong> = ButtonExtendV2.extend`<br>  color: #fff;<br>  background-color: #5cb85c;<br>  border-color: #4cae4c;<br>`<br>// ...</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfaff6a76273" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/visual-variants-for-react-components-with-styled-components-dfaff6a76273">How to create visual variants for React components using styled-components</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[Two years later, what ES6 (ES2015) features I use most]]></title>
            <link>https://medium.com/@giladaya_42364/two-years-later-what-es6-es2015-features-i-use-most-83167c690fc5?source=rss-54149ee94235------2</link>
            <guid isPermaLink="false">https://medium.com/p/83167c690fc5</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[es2015]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gilad Dayagi]]></dc:creator>
            <pubDate>Tue, 16 May 2017 07:29:44 GMT</pubDate>
            <atom:updated>2017-05-16T07:29:44.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aMnQqCLWTEO7AYEDyEHLfg.png" /></figure><p>It has been almost two years since the <a href="https://www.ecma-international.org/ecma-262/6.0/">ES6 standard</a> have been released, and thanks to tools like <a href="https://babeljs.io/">Babel</a> we didn’t have to wait for browsers support in order to adopt the new standard.<br>I have to admit that initially some of the <a href="https://github.com/lukehoban/es6features">new language features</a> seemed weird and unnecessary, but as I started to use them their benefits became clear.<br>I thought it would be an interesting exercise to review the new features and list the ones that I use the most as JS developer (of course, your list could be different..).</p><p>Each section title links to the relevant MDN documentation, and I tried to add a short example for each feature that showcases its benefits.</p><h4><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">Const</a> / <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let">Let</a></h4><p>These new declarations are block-scoped, which make good sense and is more intuitive. <br>Being able to define consts allows to be more specific with describing the intended use of the variables which in turn leads to more readable code which is safer to refactor (even though const’s can be mutated).</p><pre>const foo = {a: 1, b: 2}<br>foo.a = 3 //allowed<br>foo = {} //error</pre><h4><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a></h4><p>The intuitive scoping and minimalistic syntax make this the new go-to way of defining functions.</p><pre>const foo = name =&gt; {<br>  console.log(`Hello ${name}`)<br>}<br>foo(&#39;world&#39;)</pre><h4><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring assignment</a></h4><p>I use it mostly with objects and it really cuts-down on code repetition:</p><pre>const foo = {a: 1, b: 2, c: 3, d: 4}</pre><pre>// ES6<br>let {a, b, c} = foo</pre><pre>// ES5<br>a = foo.a<br>b = foo.b<br>c = foo.c</pre><h4><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign">Object.assign</a></h4><p>Really useful for doing immutable transformations and augmenting existing objects — for example, integrating user specified options with defaults in a library.</p><pre>const config = {a: 1, b: 2, c: 3}<br>const options = {b: 8}</pre><pre>// mutate<br>Object.assign(config, options)<br>console.log(config) // output: Object {a: 1, b: 8, c: 3}</pre><pre>// immutable update<br>const foo = {a: 1, b: 2, c: 3}<br>const bar = Object.assign({}, foo, {b: 8}, {c: 9})<br>console.log(bar) // output: Object {a: 1, b: 8, c: 9}</pre><h4><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Default_parameters">Default parameters</a></h4><p>Being able to give default values to function arguments just makes sense and was really missing from the language.<br>Saves us from using ugly code like this:</p><pre>// ES5<br>function oldWay (a, b) {<br> a = (typeof a !== &#39;undefined&#39;) ? a : &#39;foo&#39;;<br> b = (typeof b !== &#39;undefined&#39;) ? b : &#39;bar&#39;;<br> return a + b;<br>}</pre><pre>// ES6<br>function newWay (a = &#39;foo&#39;, b = &#39;bar&#39;) {<br> return a + b<br>}</pre><h4><a href="https://hacks.mozilla.org/2015/08/es6-in-depth-modules/">Modules</a></h4><p>This one is huge. We had module systems before (like CommonJs, RequireJs), but having a standard way of using modules in the browser is a big step forward. <br>Modules allow to easily structure the code in a modular way that encourages encapsulation and composability and lead to more maintainable and reusable code.</p><p>Note that this feature is not currently supported natively in any browser.</p><h4><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals">Template literals</a></h4><p>Again, this new feature just makes sense and saves us from unreadable code and excessive typing:</p><pre>const foo = 1</pre><pre>// ES5<br>const str1 = &#39;Baz: &#39;+ foo + &#39;, &#39;+ (foo + 1) + &#39;, &#39;+ (foo + 2) + &#39;, &#39;+ (foo + 3) + &#39;!&#39;</pre><pre>// ES6<br>const str2 = `Baz: ${foo}, ${foo + 1}, ${foo + 2}, ${foo + 3}!`</pre><h4><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a></h4><p>One of the ways to make async code more manageable and readable, aPromise represents a value which may be available now, or in the future, or never.</p><p>Through different library implementations, promises have shown their benefits for a while and now they are part of the standard.</p><pre>const delayed = new Promise(resolve =&gt; {<br>  setTimeout(() =&gt; {<br>    resolve()<br>  }, 500)<br>})<br>delayed.then(() =&gt; {console.log(&#39;Hello!&#39;)})<br>console.log(&#39;Wait for it...&#39;)</pre><h4><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015">Property Shorthands</a></h4><p>This is a small and simple new feature that can make the code shorter with all the benefits it brings:</p><pre>const aaa = 1, bbb = 2, ccc = 3, ddd = 4;</pre><pre>// ES5<br>const foo = {<br> aaa: aaa,<br> bbb: bbb,<br> ccc: ccc,<br> ddd: ddd,<br>}</pre><pre>// ES6<br>const bar = {<br> aaa,<br> bbb,<br> ccc,<br> ddd,<br>}</pre><p>To summarize, ES6 brought many new features into the language, and the ones listed above have proven to be very useful for me, making my life as a developer easier.<br>Most of these features are already <a href="https://kangax.github.io/compat-table/es6/">supported natively in modern browsers</a>, and there are good tools that enable support for older browsers. <br>So, in my opinion there’s really no excuse not to use them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83167c690fc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>