<?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 Dimitar Valchanov on Medium]]></title>
        <description><![CDATA[Stories by Dimitar Valchanov on Medium]]></description>
        <link>https://medium.com/@d_valchanov?source=rss-7e1ccf83f80b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w-4_OozBe9_x2MEgzxUk-w.jpeg</url>
            <title>Stories by Dimitar Valchanov on Medium</title>
            <link>https://medium.com/@d_valchanov?source=rss-7e1ccf83f80b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:54:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@d_valchanov/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[Future JavaScript #2 — Async Functions]]></title>
            <link>https://medium.com/jedi-js/future-javascript-2-async-functions-a03f0a108249?source=rss-7e1ccf83f80b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a03f0a108249</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[async-functions]]></category>
            <dc:creator><![CDATA[Dimitar Valchanov]]></dc:creator>
            <pubDate>Tue, 19 Jan 2016 07:18:34 GMT</pubDate>
            <atom:updated>2016-01-19T14:31:14.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExqUBQA5r1cN9ND0GtlNXg.jpeg" /></figure><h3>Future JavaScript #2 — Async Functions</h3><h4>A series exploring next generation JavaScript syntax</h4><p>Hey everyone, welcome to the second part of the series.</p><p>This week, we will go over and explain what Async Functions are and how we can use them to write better code. They are an ES7 proposal but we can use them today with great tools like <a href="https://babeljs.io/">Babel</a> or <a href="https://github.com/google/traceur-compiler">Traceur</a>. If you don’t know what these are, you better check them out and thank me later.</p><p>We all know how confusing callbacks can be, especially when it’s not clear what will be the order of execution and at which moment what value is available.</p><p>What Async Functions accomplish is to make asynchronous operations easier. They do that by making them look synchronous by handling them under the hood and giving us a predictable execution order.</p><p>We will cover the following:</p><ul><li><strong>Syntax</strong></li><li><strong>How they work</strong></li><li><strong>Examples</strong></li><li><strong>TL;DR</strong></li></ul><h3>Syntax</h3><p>There are two parts in specifying an Async Functions.</p><p>The first is the function itself and how it should be declared. We should use the <strong><em>async</em></strong> keyword before the function declaration. This gives us the ability to later use <strong><em>await</em></strong> in the function. For ES5, we put <strong><em>async</em></strong> before <strong><em>function. </em></strong>For ES6, we put it before the parenthesis or before the name for methods.</p><pre>// ES5<br>async function get() {}<br>async function() {}</pre><pre>// ES6<br>const get = async () =&gt; {}<br>async () =&gt; {}</pre><pre>const obj = {<br>  async get() {}<br>}</pre><p>The second part is using the <strong><em>await</em></strong> keyword in the function, which makes the execution synchronous. Since the rest of the execution will wait, we don’t have to worry that the function will return before the result is assigned.</p><pre>const post = await http.get(&quot;/posts/1&quot;);</pre><h3>How they work</h3><p>Well, let’s be honest. <strong>Using <em>await</em> doesn’t make execution synchronous, it just makes it look like it is.</strong> It just handles the Promise under the hood for us and yields the execution until it is resolved or rejected.</p><p>Even with that revelation, it’s still a big win. Now we are able to write code that looks synchronous, but is actually asynchronous. This makes one of the complex functionalities of the language simpler for everyone.</p><p>Let’s see what using <strong><em>async</em></strong> and <strong><em>await</em></strong> together looks like.</p><pre>async function get(url) {<br>  const result = await http.get(url);<br>  if (result.statusCode !== 200) alert(&quot;Something went wrong&quot;);<br>  return result;<br>}</pre><pre>get(&quot;posts&quot;).then(result =&gt; { console.log(result); });</pre><p>There are couple of things that must be clarified in order to utilise Async Functions to their full power.</p><h4>Async</h4><p>Using the keyword <strong><em>async</em></strong> accomplishes two things.</p><ul><li>Allows us to use <strong><em>await</em></strong> in the function. It’s important to remember that we can use it only directly in the function on which we set <strong><em>async</em></strong>. If we have an inner function and we want to use <strong><em>await</em></strong> in it, we should set <strong><em>async</em></strong> on it as well.</li><li>Turns everything returned from the function into a Promise. Later when the result from <strong><em>await</em></strong> arrives, the Promise is resolved with that value.</li></ul><h4>Await</h4><p>Using the <strong><em>await</em></strong> might seem strange at first but keeping the following in mind should help you reason about what is going on.</p><ul><li>In order to use <strong><em>await</em></strong>, the direct function that contains it should be <strong><em>async</em></strong>.</li><li>Internally <strong><em>await</em></strong> statements work with Promises. They just hide their implementation, making it easier to work with them.</li><li>The rest of the function continues its execution only when the Promise is resolved or rejected.</li><li>If we don’t return a Promise from the function used with <strong><em>await</em></strong>, the execution will proceed normally, as though we haven’t used <strong><em>await</em></strong> at all.</li></ul><h4>Benefits</h4><p>Synchronous programming is more simple. We can clearly see what should happen in order for certain code to execute. Also the returned results and the order in which things happen are clear.</p><p>Having the ability to think synchronously and still use the asynchronous Promises, gives us a great opportunity to make better programs and to avoid errors that are sometimes hard to spot.</p><h3>Examples</h3><p>Let’s take a look at couple of real-world examples to see how we can use async functions.</p><h4>Fetch Posts</h4><p>Let’s suppose we have a super simple http module that only fetches results from a public API in this case <a href="http://jsonplaceholder.typicode.com/">http://jsonplaceholder.typicode.com</a>.</p><p>The only way it will work with Async Functions is if it returns a Promise. Promises are nothing new, so I think there is nothing to explain here.</p><p>We will use the <strong>superagent</strong> library for the request, since it’s simple and clear.</p><pre>import request from “superagent”;</pre><pre>const BASE_URL = “<a href="http://jsonplaceholder.typicode.com/">http://jsonplaceholder.typicode.com</a>&quot;;</pre><pre>const http = {<br>  get(route) {<br>    return new Promise((resolve, reject) =&gt; {<br>      request<br>        .get(`${BASE_URL}/${route}`)<br>        .set(“Accept”, “application/json”)<br>        .end((err, res) =&gt; {<br>          if (err) {<br>            reject(err);<br>            return;<br>          }</pre><pre>          resolve(res.body);<br>        });<br>    });<br>  }<br>};</pre><p>Now when we have a way to make the request we can use it with an Async Function.</p><p>Let’s create an all purpose <strong><em>fetch</em></strong> function that takes a <strong><em>route</em></strong> parameter and handles any errors that might arise. What is important to notice is that everything is synchronous. If the Promise is resolved, we have a <strong><em>result</em></strong> with which we can do whatever we like and finally return it, so it’s passed along.</p><pre>const fetch = async route =&gt; {<br>  try {<br>    const result = await http.get(`${route}`);<br>    <em>// Do something with </em><strong><em>result</em></strong><br>    return result;<br>  } catch (err) {<br>    if (err &amp;&amp; err.response) {<br>      <em>// Handle error</em><br>    }<br>  }<br>};</pre><pre>fetch(“posts”).then(posts =&gt; {<br>  if (posts) show(posts);<br>});</pre><p>Remember that an Async Function turns whatever we return into a Promise. If there is an error and we don’t have any <strong><em>return</em></strong> statement, the function will return <strong><em>undefined</em></strong>. When the returned value is <strong><em>undefined</em></strong>, the result passed to <strong><em>then</em></strong> will be <strong><em>undefined</em></strong>, so make sure that you check for that case.</p><h4>Fetch specific posts by ID</h4><p>As we said, every time we use an <strong><em>await</em></strong> the outer function should be <strong><em>async</em></strong>.</p><p>Let’s create a function that fetches resources by the passed IDs. This is not very efficient because it will actually make several requests, instead of only one, but for the sake of this tutorial, we will do it.</p><p>It will take the route as first parameters. We can then pass variable number of IDs and will be using the rest parameters syntax to handle them.</p><pre>const fetchById = (route, ...ids) =&gt; {<br>  const posts = ids.map(async id =&gt; {<br>    try {<br>      const post = await http.get(`${route}/${id}`);<br>      <em>// Do something with </em><strong><em>post</em></strong><br>      return post;<br>    } catch (err) {<br>      if (err &amp;&amp; err.response) {<br>        <em>// Handle error</em><br>      }<br>    }<br>  });</pre><pre>  return Promise.all(posts);<br>};</pre><pre>fetchById(&quot;posts&quot;, 2, 34, 57).then((posts = []) =&gt; {<br>  posts = posts.filter(n =&gt; n);<br>  if (posts) show(posts);<br>});</pre><p>Since we are not using <strong><em>await</em></strong> in the outer function anymore we don’t need the <strong><em>async</em></strong> keyword. Now we should set it to the anonymous function we pass when we iterate over the IDs.</p><p>It’s important to remember that <strong><em>async</em></strong> should be set exactly to the function that contains the <strong><em>await</em></strong> statement or in this case to the anonymous function, and not to the outer <strong><em>fetchById</em></strong> function.</p><p>What is returned by the iteration is actually an array of promises. Then we can pass them to <strong><em>Promise.all()</em></strong>, which takes resolves only after each one has been resolved/rejected.</p><p>After that we just check and filter for any <strong><em>undefined</em></strong> posts and show them. We do this, because there is a possibility a resource with the passed ID to not exist.</p><h3>TL;DR</h3><ul><li><strong><em>async</em></strong> functions turn every returned value into Promise</li><li>to use <strong><em>await</em></strong> the direct containing function should be <strong><em>async</em></strong></li><li><strong><em>await</em></strong> should return a Promise, if not it works normally</li><li><strong><em>await</em></strong> halts execution until the Promise is resolved/rejected</li></ul><pre>const fetch = async url =&gt; {<br>  const result = await http.get(url);<br>  alert(result.length);<br>  return result;<br>}</pre><pre>fetch(&quot;posts/1&quot;).then(post =&gt; { show(post); });</pre><h3>Conclusion</h3><p>Although still a proposal and not part of the JavaScript language, we can use Async Functions today by using a transpiler. The benefits of using one don’t stop here, so if you are not, you should really try.</p><p>Async Functions give us an alternative to callbacks and makes Promises easier to use.</p><p>It’s worth taking the time to understand and start using them, not only because they are new, but because they are actually useful.</p><h4><a href="https://medium.com/jedi-js/future-javascript-d9baab4663f3#.vswnhfj5v">Table of contents</a></h4><h4>Previous Article:</h4><p><a href="https://medium.com/jedi-js/future-javascript-1-arrow-functions-f44ee4098b30#.nmgbdtocb"><strong>Arrow Functions</strong></a></p><h4>Next Article:</h4><p><strong>const / let / var</strong></p><figure><a href="https://twitter.com/dvalchanov"><img alt="" src="https://cdn-images-1.medium.com/max/320/1*VKTY67-Eb_dI-uzsAkjinA.png" /></a></figure><figure><a href="https://github.com/dvalchanov"><img alt="" src="https://cdn-images-1.medium.com/max/320/1*RndqBv4DO52q-KiX4eIFhw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a03f0a108249" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jedi-js/future-javascript-2-async-functions-a03f0a108249">Future JavaScript #2 — Async Functions</a> was originally published in <a href="https://medium.com/jedi-js">&lt; Jedi JS &gt;</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The mistakes we never made]]></title>
            <link>https://medium.com/@d_valchanov/the-mistakes-we-never-made-8f581d1e9984?source=rss-7e1ccf83f80b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f581d1e9984</guid>
            <category><![CDATA[life]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[self-improvement]]></category>
            <dc:creator><![CDATA[Dimitar Valchanov]]></dc:creator>
            <pubDate>Thu, 14 Jan 2016 13:37:01 GMT</pubDate>
            <atom:updated>2016-01-14T16:25:55.670Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0GyQ3VL9-8f_yXE1IAMow.jpeg" /></figure><h4>Accepting mistakes as part of the process</h4><p>When mistakes are possible, we stop.</p><p>And we miss.</p><p>An opportunity.</p><p>To learn. To grow. To experience. Not aware of the reward.</p><p>Next opportunity.</p><p>And we miss again.</p><p>And again.</p><p>And again.</p><p>At one point we feel something. A pull to the unknown.</p><p>And next time we go ahead. Into the unknown. And uncover the reward that mistakes bring with themselves.</p><p><strong>Being one step closer to the truth</strong>.</p><blockquote><strong>Don’t be afraid to make mistakes, be afraid not to make enough.</strong></blockquote><figure><a href="https://twitter.com/dvalchanov"><img alt="" src="https://cdn-images-1.medium.com/max/320/1*VKTY67-Eb_dI-uzsAkjinA.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f581d1e9984" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Future JavaScript #1 — Arrow Functions]]></title>
            <link>https://medium.com/jedi-js/future-javascript-1-arrow-functions-f44ee4098b30?source=rss-7e1ccf83f80b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f44ee4098b30</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Dimitar Valchanov]]></dc:creator>
            <pubDate>Tue, 12 Jan 2016 07:38:29 GMT</pubDate>
            <atom:updated>2016-01-19T07:19:54.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DehV3-eTpVhLuVms94q4A.png" /></figure><h3>Future JavaScript #1 — Arrow Functions</h3><h4>A series exploring next generation JavaScript syntax</h4><p>Hey there, I hope you all have a nice and productive week.</p><p>Arrow functions are a new addition to the language that is supposed to be an alternative to the traditional functions, in some cases.</p><p>They are very simple and powerful, but with great power comes great responsibility, so you should know exactly when to and when not to use them.</p><p>In this guide I am going to cover several parts that I think are important for a complete understanding of arrow functions:</p><ul><li><strong>Syntax</strong></li><li><strong>What is different</strong> (compared to traditional functions)</li><li><strong>Use cases</strong></li><li><strong>Rules</strong></li><li><strong>When to use / When not to use</strong></li></ul><h3>Syntax</h3><p>We all know and used the traditional function syntax a million of times:</p><pre>function() {}</pre><p>Let’s see what the new syntax looks like:</p><pre>() =&gt; {}</pre><p>You might think that it’s not worth using the new syntax, just to get rid of the `<em>function</em>` keyword.</p><p>Well, that’s not the only difference, keep reading.</p><h3>What is different</h3><p>Arrow functions have different logic compared to traditional ones. They have their advantages and disadvantages, and it’s important to understand them. Otherwise they might be very confusing to use.</p><p>Let’s go quickly through some points, to make sure you know the difference.</p><h4>Arguments</h4><p>Don’t rely on them, they are not exposed. It’s not good practice to rely on them anyway. Just use <strong>rest parameters</strong> (covered in a future guide).</p><h4>this</h4><p>Arrow functions take the context of the surrounding code. It’s inherited from the enclosing scope.</p><p>We all know that for traditional functions the context depends on where they are invoked.</p><p><strong>For arrow functions the context depends on where they are declared.</strong></p><h4>call / apply / bind</h4><p>Since the arrow functions take the surrounding context, these won’t really make a difference. Can still be used to pass parameters, but won’t change the context.</p><h4>Prototype</h4><p>Arrow functions don’t have a `<em>prototype</em>` property.</p><h4>Constructor</h4><p><strong>Arrow functions cannot be used as constructors.</strong> For that just use traditional functions, they’re well known and familiar to everyone. Or better yet, use class.</p><h4>Can’t be named</h4><p>You can use arrow functions only as anonymous functions. Or said in a different way, only use as function expressions, not as declarations.</p><pre>// NO<br>func() =&gt; {}</pre><pre>// YES<br>const func = () =&gt; {};</pre><h4>No hoisting</h4><p>Since arrow functions can be used only as expressions, there is no hoisting. Meaning that you can use it, only after it has been assigned. On the contrary, traditional function declarations are hoisted and can be used before the actual declaration.</p><pre>traditional(); // YES<br>arrow(); // Throws an Exception</pre><pre>function traditional() { console.log(&quot;ES&quot;); }<br>const arrow = () =&gt; { console.log(&quot;ES&quot;); };</pre><h3>Use cases</h3><p>Let’s go through some examples on how you can actually use arrow functions. Let’s also see how a traditional function would be used compared to an arrow function, if comparable at all.</p><h4><strong>IIFE</strong></h4><p>Calling a function immediately after declaring it is a good practice for providing scope and not polluting the global object. The same can be achieved with arrow functions.</p><p>Just don’t forget to surround it with parenthesis. It looks confusing without ones.</p><pre><em>// ES5</em><br>(function() {<br>  ...<br>})();</pre><pre>-&gt;</pre><pre><em>// ES6</em><br>(() =&gt; {<br>  ...<br>})();</pre><pre><br>// NO<br>(() =&gt; {}());</pre><h4><strong>Shorthand</strong></h4><p>The shorthand syntax is something you will fall in love with. It’s super conscious and easy to read and saves you some code. Essentially, you skip the parenthesis, and the `<em>function</em>` and `<em>return</em>` keyword.</p><pre><em>// ES5</em><br>array.map(function(x) { return x * x });</pre><pre>-&gt;</pre><pre><em>// ES6</em><br>array.map(x =&gt; x * x);</pre><p><strong>Remember:</strong></p><ul><li>you can skip the return statement only if using them on one line</li><li>use it only when you have one statement (which will be returned)</li></ul><h4>Class</h4><p>Since the arrow function uses the surrounding context it’s safe to use it as a way to bind the function to the context of the class. No more worries when passing it as callback.</p><pre>class Button {<br>  constructor() {<br>    super();<br>    document.addEventListener(&quot;click&quot;, this._addClick, false);<br>  }<br>  <br>  clickCounter = 0;</pre><pre>  _addClick = () =&gt; {<br>    this.clickCounter += 1;<br>  };<br>}</pre><p><strong>Remember</strong>:</p><ul><li>if you want to pass different context, use traditional method</li></ul><h4>Async</h4><p>Async Functions. This is a great and powerful new concept as well. Essentially, you use them when you have a Promise that needs to be resolved or rejected. By using them we don’t have to pass callback functions and the code looks much cleaner. (Stay tuned for a guide on these soon)</p><pre>const getter = async (url) =&gt; {<br>  return await http.get(url);<br>};</pre><h4>Returned functions</h4><p>JavaScript‘s power comes from its functional nature, the fact that functions are first-class objects. Which means you can return them. And that’s a powerful pattern that is used often. You can use arrow functions to make it look even more impressive.</p><pre><em>// ES5</em><br>function onPower(exponent) {<br>  return function(number) {<br>    return Math.pow(number, exponent);<br>  };<br>}</pre><pre>const square = onPower(2);<br>square(5); <em>// 25</em></pre><pre>-&gt;</pre><pre><em>// ES6</em><br><em>// One line</em><br>const onPower = exponent =&gt; number =&gt; Math.pow(number, exponent);</pre><pre>// Multiple lines<br>const onPower = exponent =&gt; number =&gt; {<br>  return Math.pow(number, exponent);<br>};</pre><h3>Rules</h3><p>There are certain rules that, if followed, will make your life easier when using arrow functions.</p><h4>One line</h4><p><strong>Skip the curly braces and the return statement.</strong> Skipping the `<em>return</em>` statement works only for single expression though, so be careful to not forget it otherwise.</p><pre>array.map(x =&gt; x * x);</pre><p>If you have anything other than a single expression, use within a block.</p><pre>array.map(x =&gt; { if (typeof x === “number”) return x * x });</pre><h4>Multiple lines</h4><p><strong>Use with the curly braces and explicit return.</strong> Works like traditional functions, if you don’t use the `<em>return</em>` statement, the returned value is <em>undefined</em>.</p><pre>array.map(x =&gt; {<br>  if (x % 2 === 0) return x;<br>  return x * x;<br>});</pre><h4>No parameters</h4><p><strong>Use with parenthesis</strong>. Using it without ones will break it.</p><pre>let counter = 0;</pre><pre>array.forEach(() =&gt; { <br>  counter += 1;<br>});</pre><h4>One parameter</h4><p><strong>Skip the parenthesis</strong>. Feel free to use them, but they are not needed and it looks better without ones.</p><pre>let container = [];</pre><pre>array.forEach(value =&gt; {<br>  container.push(value);<br>});</pre><h4>Multiple parameters</h4><p><strong>Use with parenthesis</strong>. If not used it actually thinks that we are passing one parameter and one arrow function, separated by a comma. So if you have two or more parameters, always wrap them in parenthesis.</p><pre>let obj = {};</pre><pre>array.forEach((value, index) =&gt; {<br>  obj[value] = index;<br>});</pre><h4>Returning an object</h4><p><strong>Surround with parenthesis</strong>. Object literal and arrow function both use blocks, so if you want to return an object with the shorthand syntax, surround it with parenthesis.</p><pre>array.map(x =&gt; ({ foo: x }));</pre><p>Or returning an empty object:</p><pre>const empty = () =&gt; ({});</pre><h4>Arguments</h4><p><strong>Don’t use with arguments</strong>. Prefer the <em>rest parameters</em> syntax, since it better shows your intentions and let’s admit it… it looks sexier.</p><pre>const add = (...numbers) =&gt; {<br>  return numbers.reduce((x, y) =&gt; x + y);<br>};</pre><pre>// one line<br>const add = (...numbers) =&gt; numbers.reduce((x, y) =&gt; x + y);</pre><pre>add(1, 2, 3);</pre><h4>Side effects</h4><p><strong>Use with block</strong>. If you want to use it on one line but don’t really have anything to return, just surround the expression with curly braces to explicitly show that.</p><pre>let counter = 0;</pre><pre>array.forEach(x =&gt; { counter += 1; });</pre><p>Using it without curly braces looks confusing. Do you want to return? And actually what are you returning? Just check that, doesn’t look good at all.</p><pre>// NO<br>array.forEach(x =&gt; counter += 1);</pre><h3>When to use</h3><p>The new arrow function is not one-size-fit-all type of function. So it’s important to know when it’s safe to use it.</p><ul><li>When you want to use the surrounding context</li><li>When the context is not important</li><li>When the shorthand syntax makes sense</li></ul><h3>When not to use</h3><p>It’s important to also know when not to use arrow functions.</p><ul><li>Constructors</li><li>In the global scope</li><li>When you want to change the context on execution</li><li>When you want to use the prototype</li></ul><p>That pretty much sums it up. I hope this was helpful to everyone who is just starting or wants to understand arrow function in more depth.</p><h4><a href="https://medium.com/jedi-js/future-javascript-d9baab4663f3#.vswnhfj5v">Table of contents</a></h4><h4>Next Article:</h4><p><a href="https://medium.com/jedi-js/future-javascript-2-async-functions-a03f0a108249#.2mp7xd2pw"><strong>Async Functions</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*VKTY67-Eb_dI-uzsAkjinA.png" /></figure><figure><a href="https://github.com/dvalchanov"><img alt="" src="https://cdn-images-1.medium.com/max/320/1*RndqBv4DO52q-KiX4eIFhw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f44ee4098b30" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jedi-js/future-javascript-1-arrow-functions-f44ee4098b30">Future JavaScript #1 — Arrow Functions</a> was originally published in <a href="https://medium.com/jedi-js">&lt; Jedi JS &gt;</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Future JavaScript]]></title>
            <link>https://medium.com/jedi-js/future-javascript-d9baab4663f3?source=rss-7e1ccf83f80b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9baab4663f3</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[future]]></category>
            <dc:creator><![CDATA[Dimitar Valchanov]]></dc:creator>
            <pubDate>Tue, 12 Jan 2016 07:36:51 GMT</pubDate>
            <atom:updated>2016-01-19T07:21:14.748Z</atom:updated>
            <content:encoded><![CDATA[<h3>Future JavaScript #0 — Introduction</h3><h4>A series exploring next generation JavaScript syntax</h4><p>Every JavaScript developer wants to be up-to-date with the latest technologies, but when you are too busy it’s just not easy. How do you start and where do you find a detailed explanation?</p><p>This is an introduction for a type of series, in which I want to provide a detailed explanation of the next generation JavaScript syntax.</p><p>This will be a detailed guide for the most important functionality.</p><p>A guide that will be enough to make you confident about using it.</p><p>A guide that explains everything you will need to know.</p><p>Ok, enough fluff talk, let’s get started.</p><p>Let’s see what will be covered in the series. The content will be updated with every published article.</p><h4>Table of Contents:</h4><ol><li><a href="https://medium.com/jedi-js/future-javascript-1-arrow-functions-f44ee4098b30#.jq3ahyvo8"><strong>Arrow Functions</strong></a></li><li><a href="https://medium.com/jedi-js/future-javascript-2-async-functions-a03f0a108249#.2mp7xd2pw"><strong>Async Functions</strong></a></li><li>const / let / var</li><li>Default parameters / Computed properties</li><li>Property methods / Shorthand properties</li><li>Destructuring / Spread</li><li>Template literals</li><li>Decorators</li><li>Modules</li><li>Classes</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*VKTY67-Eb_dI-uzsAkjinA.png" /></figure><figure><a href="https://github.com/dvalchanov"><img alt="" src="https://cdn-images-1.medium.com/max/320/1*RndqBv4DO52q-KiX4eIFhw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9baab4663f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jedi-js/future-javascript-d9baab4663f3">Future JavaScript</a> was originally published in <a href="https://medium.com/jedi-js">&lt; Jedi JS &gt;</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2048 game — Implemented with React and Redux]]></title>
            <link>https://medium.com/@d_valchanov/2048-game-implemented-with-react-and-redux-6b96bbcf4241?source=rss-7e1ccf83f80b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b96bbcf4241</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Dimitar Valchanov]]></dc:creator>
            <pubDate>Sat, 09 Jan 2016 08:46:48 GMT</pubDate>
            <atom:updated>2016-01-14T16:28:47.358Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are a Javascript developer, you most probably have heard of React. It helps you build modular applications that scale well. And the best part, you can use it for everything — websites, mobile applications and server rendering — just name it.</p><p>Unfortunately, it’s only the visible part of the application, the part that keeps up to date on state changes. But for that to happen we first need a place to save our state.</p><p>And that’s where Redux, which is a Flux implementation, comes in. It contains the application’s state, helping us to easily manipulate it. The data flow is unidirectional, making it easy to understand and predict. And in addition, it gives us some cool functionality like hot reload and time travel.</p><p>There are other implementations of these two, but for me the big advantage to start using them is the great community that is always willing to help, the abundance of resources that can get you started and a technology that is rapidly evolving and getting better. Not bad at all.</p><h3>2048</h3><p>I started using React and Redux a couple of months ago myself, but I think the best way to understand them even better is to try to explain them to other people and to build something a little different, in this case a game. I have chosen the 2048 game by <a href="https://medium.com/u/c1e0c9be7c55">Gabriele Cirulli</a>, because it’s fun and I personally have spent considerable amount of time getting to that sacred 2048 tile.</p><p>I’ve added little twist to the game, by introducing a gift tile (well, it was Christmas, gifts everywhere) that can be merged with any other tile, doubling its value. The chance for this tile to appear would be 1%.</p><p>The final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*tEPZNjszsEzeNtFV1NUF1A.png" /></figure><p>This is not going to be a guide. I am just going over the technologies used and some code samples. I’ve always thought that the best way to learn a new technology is to actually use it or try to understand the code of other developers. That’s why I strongly suggest you to check the <a href="https://github.com/dvalchanov/react-redux-2048">repository</a>. It is thoroughly documented and you should have no problems reason about what each piece of code accomplishes.</p><p>Or you can check the end result in this <a href="http://dvalchanov.github.io/react-redux-2048/">DEMO</a>.</p><p>The goal of this game was to try something new. There are a lot of parts that can be improved, so feel free to contribute.</p><h4>Technology Stack</h4><p>React and Redux are great, but to get the best out of them we will use them with other tools.</p><p><strong><em>Webpack<br></em></strong>A module bundler, letting us split our code. Has great and easy integration with 3rd party loaders and plugins and is easily customisable.</p><p><strong><em>Babel<br></em></strong>A compiler, letting us write the latest version of JavaScript today. We are going to use it to write ES2015 and to even use decorators. It also has support for React, letting us transpile JSX to JS.</p><p><strong><em>ImmutableJS<br></em></strong>An immutable data collection, making it plain simple to track any changes in the state.</p><p><strong><em>ESLint<br></em></strong>A JavaScript linter, helping us keep best practices and preventing us from making errors. It has very useful ES2015 and React rules, which are going to be helpful in making the code consistent.</p><h4>Structure</h4><p>The directory structure is self-explanatory and expected:</p><pre>- src/<br>  - images/<br>  - styles/<br>  - scripts/<br>    - actions/<br>    - components/<br>    - containers/<br>    - reducers/<br>    - utils/<br>    - helpers.js    <br>    - main.js</pre><p><strong><em>main.js</em></strong> — an entry point file for the application. We connect our module bundler to this file, so it can have access to everything connected as well.</p><p><strong><em>helper.js</em></strong> — helper functions, directly tied to this game.</p><p><strong><em>containers/</em> </strong>— containing all top level components. Most of the time we can think of containers as pages. In this case we have only one page, which is the game but usually in a more complex application we would have more of these.</p><p><strong><em>components/</em></strong> — the building blocks of our application. Here we are going to have our Board, which is going to contain a Grid, that is later going to be filled with Tiles, with which the game is played.</p><p><strong><em>actions/</em></strong> — all actions that are expected to happen in our application. No changes should be made to the state, unless they are made with the actions that we declare here.</p><p><strong><em>reducers/</em></strong> — the place where we explain how the application state should change in accordance to the called actions. This is the only place where the state can be changed.</p><p><strong><em>utils/</em></strong> — utility functions helping us to extract common functionality. These are abstract ones, that can be easily used in another application as well.</p><h4>Code Samples</h4><p>Let’s look at some code samples. This is not a guide, so I am just going over my thought process when implementing these.</p><p><strong>Initial State</strong></p><p>When we start a Redux implementation, it’s really important to know what our state is going to look like. This can help us with getting a better perspective of the application. There’s no way to know every bit of functionality we are going to need, but we can at least figure out the core.</p><p>In this game we know that we need to track if the player has won. We have two states for that — win or lose, so we can use a boolean — `<em>true</em>` and `<em>false</em>`. And a default value of `<em>null</em>` when the final result is not known yet.</p><p>There is also score in this game and we need a way to track it, starting from zero.</p><pre>const defaultState = Map({<br>  win: null,<br>  score: 0<br>});</pre><p>For the actual implementation of the game we have empty cells that need to be filled with tiles. We are going to separate them, because by having a collection of empty cells, we can easily choose random cell that should be filled with a tile. Then we just remove that cell from the collection.</p><p>That cell is not actually removed, it’s just moved in the grid. The grid is the actual representation of the game board. It contains arrays of arrays, each one representing a cell and each one being filled with tiles, which positions we get from the cells collection.</p><p>`<em>generateCells</em>` and `<em>generateGrid</em>` are just generators that iterate over the size of the board and create the corresponding structure.</p><pre>const defaultState = Map({<br>  win: null,<br>  score: 0,<br>  cells: generateCells(SIZE),<br>  grid: generateGrid(SIZE)<br>});</pre><p>Another thing we need is to save the game and it would be useful to have a property that specifies the difference between a saved and currently played game.</p><p>Also we need a method that checks if there is a saved game. If there is such it will load its state, if not it will just use the default state.</p><pre>const defaultState = Map({<br>  win: null,<br>  score: START_SCORE,<br>  cells: generateCells(SIZE, SIZE),<br>  grid: generateGrid(SIZE, SIZE),<br>  fromSaved: false<br>});</pre><pre>const initialState = startSavedGame() || defaultState;</pre><p><strong>Adding a Tile</strong></p><p>As we already know, we have empty cells collection from where we can choose a random empty cell with its position and move it in the grid, which represents the actual board (the new tile will appear on screen only when in the grid).</p><p>With ImmutableJS, we are updating the cell positioned in the path specified by the first parameter (for example <em>[‘grid’, 0, 1]</em>). After that the found cell is passed in the callback function and we add our new tile to it. Since the presentation of the tile initially is just its position, we are also adding an `<em>id</em>` which is tracked and lets us later use it as key for each React component. We are also adding the value of the tile, which can be either a passed value (when we are merging two tiles) or the initial value (which is 2).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/411bb9d5d620f2a44eb8e086c1ee36bb/href">https://medium.com/media/411bb9d5d620f2a44eb8e086c1ee36bb/href</a></iframe><p><strong>Stateless Components</strong></p><p>In the end of each game we need to show an overlay over the board with a message and a new game button. This sounds like a very simple component, it just takes data and shows it and doesn’t need to hold any state. And because of that we can use a stateless component, which is just a pure function that returns JSX, like the `<em>render()</em>` method.</p><p>We have a function, taking two arguments — the win state and a new game callback function, which is going to be handled by the parent component. We are passing a callback, because if we do the same for other components as well, we will have all the logic in one place and the components will be just simple and pure representations of the state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dbee6f14911458b183c3b657eb7df8c/href">https://medium.com/media/5dbee6f14911458b183c3b657eb7df8c/href</a></iframe><h4>Conclusion</h4><p>I think that covers, some interesting parts of the game. For me it was a lot of fun working on it. It allowed me to better understand how the used libraries work together and to get experience building something different — a game.</p><p>Hope you all have a fun weekend.</p><p><a href="https://github.com/dvalchanov/react-redux-2048">dvalchanov/react-redux-2048</a></p><p><a href="http://dvalchanov.github.io/react-redux-2048/">DEMO</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*VKTY67-Eb_dI-uzsAkjinA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b96bbcf4241" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>