<?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[ECMAScript 2015 - Medium]]></title>
        <description><![CDATA[Let’s talk about ES6 - Medium]]></description>
        <link>https://medium.com/ecmascript-2015?source=rss----c8958ce340e4---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>ECMAScript 2015 - Medium</title>
            <link>https://medium.com/ecmascript-2015?source=rss----c8958ce340e4---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 30 May 2026 16:47:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/ecmascript-2015" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[ES6 — set, map, weak]]></title>
            <link>https://medium.com/ecmascript-2015/es6-set-map-weak-a2aeb7e2d384?source=rss----c8958ce340e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/a2aeb7e2d384</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Maciej Rzepiński]]></dc:creator>
            <pubDate>Fri, 19 Jun 2015 09:07:48 GMT</pubDate>
            <atom:updated>2015-06-19T09:07:48.142Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*RQFLsbQumE-iNrXzs_Oz8g.jpeg" /></figure><h2>ES6 — set, map, weak</h2><h3>Let’s talk about ECMAScript 2015</h3><p>Previous</p><p><a href="https://medium.com/p/9ca8d8b4aca6"></a></p><p>Sets and maps will be (are) finally available in ES6! No more spartan way to manipulate data structures. This chapter explains how we can deal with <strong>Map</strong>, <strong>Set</strong>, <strong>WeakMap</strong> and <strong>WeakSet</strong>.</p><h4>Map</h4><p>Maps are a store for <strong>key</strong> / <strong>value</strong> pairs. Key and value could be a primitives or object references.</p><p>Let’s create a map:</p><pre>let map = new <strong>Map</strong>(),<br>    val2 = &#39;val2&#39;,<br>    val3 = {<br>      key: &#39;value&#39;<br>    };</pre><pre>map.<strong>set</strong>(0, &#39;val1&#39;);<br>map.<strong>set</strong>(&#39;1&#39;, val2);<br>map.<strong>set</strong>({ key: 2 }, val3);</pre><pre>console.log(map); // Map {0 =&gt; &#39;val1&#39;, &#39;1&#39; =&gt; &#39;val2&#39;, Object {key: 2} =&gt; Object {key: &#39;value&#39;}}</pre><p>We can also use a constructor to create the sam map, based on array param passed to the constructor:</p><pre>let map,<br>    val2 = &#39;val2&#39;,<br>    val3 = {<br>      key: &#39;value&#39;<br>    };</pre><pre>map = new <strong>Map</strong>(<strong>[</strong>[0, &#39;val1&#39;], [&#39;1&#39;, val2], [{ key: 2 }, val3]<strong>]</strong>);</pre><pre>console.log(map); // Map {0 =&gt; &#39;val1&#39;, &#39;1&#39; =&gt; &#39;val2&#39;, Object {key: 2} =&gt; Object {key: &#39;value&#39;}}</pre><p>To get a value by using a key, we have to use a <strong>get()</strong> method to do it (surprising):</p><pre>let map = new Map(),<br>    val2 = &#39;val2&#39;,<br>    val3 = {<br>      key: &#39;value&#39;<br>    };</pre><pre>map.set(0, &#39;val1&#39;);<br>map.set(&#39;1&#39;, val2);<br>map.set({ key: 2 }, val3);</pre><pre>console.log(map.<strong>get</strong>(&#39;1&#39;)); // val2</pre><p>To iterate over the map collection, we can use built-in <strong>forEach</strong> method or use new <strong>for..of</strong> structure:</p><pre>// <strong>forEach</strong><br>let map = new Map(),<br>    val2 = &#39;val2&#39;,<br>    val3 = {<br>      key: &#39;value&#39;<br>    };</pre><pre>map.set(0, &#39;val1&#39;);<br>map.set(&#39;1&#39;, val2);<br>map.set({ key: 2 }, val3);</pre><pre>map.<strong>forEach</strong>(function (value, key) {<br>  console.log(`Key: ${key} has value: ${value}`);<br>  // Key: 0 has value: val1<br>  // Key: 1 has value: val2<br>  // Key: [object Object] has value: [object Object] <br>});</pre><pre>// <strong>for..of</strong><br>let map = new Map(),<br>    val2 = &#39;val2&#39;,<br>    val3 = {<br>      key: &#39;value&#39;<br>    };</pre><pre>map.set(0, &#39;val1&#39;);<br>map.set(&#39;1&#39;, val2);<br>map.set({ key: 2 }, val3);</pre><pre><strong>for</strong> (let entry <strong>of</strong> map) {<br>  console.log(`Key: ${entry[0]} has value: ${entry[1]}`);<br>  // Key: 0 has value: val1<br>  // Key: 1 has value: val2<br>  // Key: [object Object] has value: [object Object] <br>};</pre><p>We can also use a couple of methods to iterate:</p><ul><li><strong>entries()</strong> — get all entries</li><li><strong>keys()</strong> — get only all keys</li><li><strong>values()</strong> — get only all values</li></ul><p>To check if value is stored in our map, we can use <strong>has()</strong> method:</p><pre>let map = new Map(),<br>    val2 = &#39;val2&#39;,<br>    val3 = {<br>      key: &#39;value&#39;<br>    };</pre><pre>map.set(0, &#39;val1&#39;);<br>map.set(&#39;1&#39;, val2);<br>map.set({ key: 2 }, val3);</pre><pre>console.log(map.<strong>has</strong>(0));     // true<br>console.log(map.<strong>has</strong>(&#39;key&#39;)); // false</pre><p>To delete entry, we have <strong>delete()</strong> method:</p><pre>let map = new Map(),<br>    val2 = &#39;val2&#39;,<br>    val3 = {<br>      key: &#39;value&#39;<br>    };</pre><pre>map.set(0, &#39;val1&#39;);<br>map.set(&#39;1&#39;, val2);<br>map.set({ key: 2 }, val3);</pre><pre>console.log(map.<strong>size</strong>); // <strong>3</strong></pre><pre>map.<strong>delete</strong>(&#39;1&#39;);</pre><pre>console.log(map.<strong>size</strong>); // <strong>2</strong></pre><p>..and to clear all collection, we use <strong>clear()</strong> method:</p><pre>let map = new Map(),<br>    val2 = &#39;val2&#39;,<br>    val3 = {<br>      key: &#39;value&#39;<br>    };</pre><pre>map.set(0, &#39;val1&#39;);<br>map.set(&#39;1&#39;, val2);<br>map.set({ key: 2 }, val3);</pre><pre>console.log(map.<strong>size</strong>); // <strong>3</strong></pre><pre>map.<strong>clear</strong>();</pre><pre>console.log(map.<strong>size</strong>); // <strong>0</strong></pre><h4>Set</h4><p>It’s a collection for <em>unique</em> values. The values could be also a primitives or object references.</p><pre>let set = new <strong>Set</strong>();</pre><pre>set.<strong>add</strong>(1);<br>set.<strong>add</strong>(&#39;1&#39;);<br>set.<strong>add</strong>({ key: &#39;value&#39; });</pre><pre>console.log(set); // Set {1, &#39;1&#39;, Object {key: &#39;value&#39;}}</pre><p>Like a map, set allows to create collection by passing an array to its constructor:</p><pre>let set = new <strong>Set</strong>(<strong>[</strong>1, &#39;1&#39;, { key: &#39;value&#39; }<strong>]</strong>);</pre><pre>console.log(set); // Set {1, &#39;1&#39;, Object {key: &#39;value&#39;}}</pre><p>To iterate over sets we have the same two options — built-in <strong>forEach</strong> function or <strong>for..of</strong> structure:</p><pre>// <strong>forEach</strong><br>let set = new Set([1, &#39;1&#39;, { key: &#39;value&#39; }]);</pre><pre>set.<strong>forEach</strong>(function (value) {<br>  console.log(value);<br>  // 1<br>  // &#39;1&#39;<br>  // Object {key: &#39;value&#39;}<br>});</pre><pre>// <strong>for..of</strong><br>let set = new Set([1, &#39;1&#39;, { key: &#39;value&#39; }]);</pre><pre><strong>for</strong> (let value <strong>of</strong> set) {<br>  console.log(value);<br>  // 1<br>  // &#39;1&#39;<br>  // Object {key: &#39;value&#39;}<br>};</pre><blockquote><strong>Set</strong> doesn’t allow to add duplicates.</blockquote><pre>let set = new <strong>Set</strong>([1, 1, 1, 2, 5, 5, 6, 9]);<br>console.log(set.size); // <strong>5!</strong></pre><p>We can also use <strong>has()</strong>, <strong>delete()</strong>, <strong>clear()</strong> methods, which are similar to the Map versions.</p><h4>WeakMap</h4><p>WeakMaps provides leak-free object keyed side tables. It’s a Map that doesn’t prevent its keys from being <strong>garbage-collected</strong>. We don’t have to worry about memory leaks.</p><p>If the object is destroyed, the garbage collector removes an entry from the WeakMap and frees memory.</p><blockquote><strong>Keys</strong> must be objects.</blockquote><p>It has almost the same API like a Map, but we <strong>can’t iterate</strong> over the WeakMap collection. We can’t even determine the length of the collection because we don’t have <strong>size</strong> attribute here.</p><p>The API looks like this:</p><pre>new WeakMap([iterable])</pre><pre>WeakMap.prototype.get(key)        : any<br>WeakMap.prototype.set(key, value) : this<br>WeakMap.prototype.has(key)        : boolean<br>WeakMap.prototype.delete(key)     : boolean</pre><pre>let wm = new <strong>WeakMap</strong>(),<br>    obj = {<br>      key1: {<br>        k: &#39;v1&#39;<br>      },<br>      key2: {<br>        k: &#39;v2&#39;<br>      }<br>   };</pre><pre>wm.set(obj.key1, &#39;val1&#39;);<br>wm.set(obj.key2, &#39;val2&#39;);</pre><pre>console.log(wm); // WeakMap {Object {k: &#39;v1&#39;} =&gt; &#39;val1&#39;, Object {k: &#39;v2&#39;} =&gt; &#39;val2&#39;}<br>console.log(wm.has(obj.key1)); // <strong>true</strong></pre><pre><strong>delete</strong> obj.key1;</pre><pre>console.log(wm.has(obj.key1)); // <strong>false</strong></pre><h4>WeakSet</h4><p>Like a WeakMap, WeakSet is a Seat that doesn’t prevent its values from being garbage-collected. It has simpler API than WeakMap, because has only three methods:</p><pre>new WeakSet([iterable])</pre><pre>WeakSet.prototype.add(value)    : any<br>WeakSet.prototype.has(value)    : boolean<br>WeakSet.prototype.delete(value) : boolean</pre><blockquote><strong>WeakSets</strong> are collections of <strong>unique objects only</strong>.</blockquote><p>WeakSet collection can‘t be <strong>iterated</strong> and we cannot determine its <strong>size</strong>.</p><pre>let ws = new <strong>WeakSet</strong>(),<br>    obj = {<br>      key1: {<br>        k: &#39;v1&#39;<br>      },<br>      key2: {<br>        k: &#39;v2&#39;<br>      }<br>   };</pre><pre>ws.add(obj.key1);<br>ws.add(obj.key2);</pre><pre>console.log(ws); // WeakSet {Object {k: &#39;v1&#39;}, Object {k: &#39;v2&#39;}}<br>console.log(ws.has(obj.key1)); // <strong>true</strong></pre><pre><strong>delete</strong> obj.key1;</pre><pre>console.log(ws.has(obj.key1)); // <strong>false</strong></pre><h4>THE END!</h4><p>Of course not! ECMAScript 2015 (ES6) has more than described by me in <strong>Let’s talk about ECMAScript 2015</strong> series. Feel free to independently explore and try by your own the new possibilities offered by the <strong>JavaScript</strong> language.</p><blockquote>It’s finally here!</blockquote><p><a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">Standard ECMA-262</a></p><blockquote>Like it? <strong>Recommend it!</strong></blockquote><p><a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a></p><blockquote>Whole series is also available as an <strong>ebook</strong>. I published it on <a href="http://leanpub.com">leanpub.com</a></blockquote><p><a href="https://leanpub.com/ecmascript2015es6guide">ECMAScript 2015 guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbGHEO5gdr_MVNiYQLvK9A.jpeg" /></figure><p>Future is bright!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2aeb7e2d384" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ecmascript-2015/es6-set-map-weak-a2aeb7e2d384">ES6 — set, map, weak</a> was originally published in <a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 — promises]]></title>
            <link>https://medium.com/ecmascript-2015/es6-promises-9ca8d8b4aca6?source=rss----c8958ce340e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/9ca8d8b4aca6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Maciej Rzepiński]]></dc:creator>
            <pubDate>Wed, 10 Jun 2015 16:19:29 GMT</pubDate>
            <atom:updated>2016-04-17T07:09:10.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*RQFLsbQumE-iNrXzs_Oz8g.jpeg" /></figure><h2>ES6 — promises</h2><h3>Let’s talk about ECMAScript 2015</h3><p>Previous</p><p><a href="https://medium.com/p/d5646d1b9a08"></a></p><p><strong>Promises</strong> aren’t a new and shiny idea. I use it every day in my <a href="https://docs.angularjs.org/api/ng/service/$q">AngularJS</a> code. It’s based on <a href="https://github.com/kriskowal/q">kriskowal / <strong>q</strong></a> library:</p><blockquote>A tool for creating and composing asynchronous promises in JavaScript.</blockquote><p>It’s a library for asynchronous programming, to make our life easier. But, before I describe promises, I have to write something about callbacks.</p><h4>Callbacks and callback hell</h4><p>Until I remember, JavaScript coders use callbacks for all browser-based asynchronous functions (setTimeout, XMLHttpRequest, etc.).</p><p>Look at naive example:</p><pre>console.log(&#39;start!&#39;);<br>setTimeout(function () {<br>  console.log(&#39;ping&#39;);<br>  setTimeout(function () {<br>    console.log(&#39;pong&#39;);<br>    setTimeout(function () {<br>      console.log(&#39;end!&#39;);<br>    }, 1000);<br>  }, 1000);<br>}, 1000);</pre><pre>// start!<br>// after 1 sec: ping<br>// .. 1 sec later: pong<br>// .. and: end!</pre><p>We have simple code which prints some statements to the console. I used a <strong>setTimeout</strong> function here, to show callback functions passed to invoke later (1 sec here). It looks terrible and we have only 3 steps here. Let’s imagine more steps. It will look like you build a pyramid, not nice, readable code. Awful, right? It’s called <strong>callback hell</strong> and we have it everywhere.</p><p><a href="http://callbackhell.com/">Callback Hell</a></p><h4>Promises</h4><p>Support for promises is a very nice addition to the language. It’s finally native in the ES6.</p><blockquote>Promises are a first class representation of a value that may be made available in the future.</blockquote><p>A promise can be:</p><ul><li><strong>fulfilled</strong> —promise succeeded</li><li><strong>rejected</strong> —promise failed</li><li><strong>pending </strong>— not fulfilled or not rejected yet</li><li><strong>settled </strong>— fulfilled or rejected</li></ul><p>Every returned <strong>promise object</strong> also has a <strong>then</strong> method to execute code when a promise is <strong>settled</strong>.</p><p>Yep, promise <strong>object</strong>, because..</p><blockquote>callbacks are functions, promises are objects.</blockquote><p>Callbacks are blocks of code to execute in response to.. something (event). Promises are objects which store an information about the state.</p><p>How does it look like? Let’s see:</p><pre>new <strong>Promise</strong>((<strong>resolve</strong>, <strong>reject</strong>) =&gt; {<br>  // when success, resolve<br>  let value = &#39;success&#39;;<br>  <strong>resolve</strong>(value);<br> <br>  // when an error occurred, reject<br>  <strong>reject</strong>(new Error(&#39;Something happened!&#39;));<br>});</pre><p>Promise calls its <strong>resolve function</strong> when it’s fulfilled (success) and <strong>reject function</strong> otherwise (failure).</p><p>Promises are objects, so it’s not passed as arguments like callbacks, it’s <strong>returned</strong>. The return statement is an object which is a <em>placeholder</em> for the result, which will be available in the future.</p><p>Promises have just one responsibility — <strong>they represent only one event</strong>. Callbacks can handle multiple events, many times.</p><p>We can assign returned value (object) to the <strong>let statement</strong>:</p><pre>let promise = new <strong>Promise</strong>((<strong>resolve</strong>, <strong>reject</strong>) =&gt; {<br>  // when success, resolve<br>  let value = &#39;success&#39;;<br>  <strong>resolve</strong>(value);<br> <br>  // when an error occurred, reject<br>  <strong>reject</strong>(new Error(&#39;Something happened!&#39;));<br>});</pre><p>As I mentioned above — promise object also has a <strong>then</strong> method to execute code when the promise is settled.</p><pre>promise.<strong>then</strong>(onResolve, onReject)</pre><p>We can use this function to handle <strong>onResolve</strong> and <strong>onReject</strong> values returned by a promise. We can handle <strong>success</strong>, <strong>failure</strong> or <strong>both</strong>.</p><pre>let promise = new Promise((resolve, reject) =&gt; {<br>  // when success, resolve<br>  let value = &#39;success&#39;;<br>  resolve(value);<br> <br>  // when an error occurred, reject<br>  reject(new Error(&#39;Something happened!&#39;));<br>});</pre><pre>promise.<strong>then</strong>(response =&gt; {<br>  console.log(response);<br>}, error =&gt; {<br>  console.log(error);<br>});</pre><pre>// success</pre><p>Our code above never executes <strong>reject</strong> function, so we can omit it for simplicity:</p><pre>let promise = new Promise(resolve =&gt; {<br>  let value = &#39;success&#39;;<br>  resolve(value);<br>});</pre><pre>promise.<strong>then</strong>(response =&gt; {<br>  console.log(response); // success<br>});</pre><p>Handlers passed to <strong>promise.then</strong> don’t just handle the result of the previous promise — their return is turned into a <strong>new promise</strong>.</p><pre>let promise = new Promise(resolve =&gt; {<br>  let value = &#39;success&#39;;<br>  resolve(value);<br>});</pre><pre>promise.<strong>then</strong>(response =&gt; {<br>  console.log(response); // success<br>  return &#39;another success&#39;;<br>}).<strong>then</strong>(response =&gt; {<br>  console.log(response); // another success <br>});</pre><p>You can see, that the code based on promises is always <em>flat</em>. No more <strong>callback hell</strong>.</p><p>If you are only interested in rejections, you can omit the first parameter.</p><pre>let promise = new Promise((resolve, reject) =&gt; {<br>  let reason = &#39;failure&#39;;<br>  reject(reason);<br>});</pre><pre>promise.<strong>then</strong>(<br>  <strong>null</strong>,<br>  error =&gt; {<br>    console.log(error); // failure<br>  }<br>);</pre><p>But is a more compact way of doing the same thing —<strong> catch()</strong> method.</p><pre>let promise = new Promise((resolve, reject) =&gt; {<br>  let reason = &#39;failure&#39;;<br>  reject(reason);<br>});</pre><pre>promise.<strong>catch</strong>(err =&gt; {<br>  console.log(err); // failure<br>});</pre><p>If we have more than one <strong>then()</strong> call, the error is passed on until there is an error handler.</p><pre>let promise = new Promise(resolve =&gt; {<br>  resolve();<br>});</pre><pre>promise<br>  .<strong>then</strong>(response =&gt; {<br>    return 1;<br>  })<br>  .<strong>then</strong>(response =&gt; {<br>    throw new Error(&#39;failure&#39;);<br>  })<br>  .<strong>catch</strong>(error =&gt; {<br>    console.log(error.message); // failure<br>  });</pre><p>We can even combine <strong>one or more promises</strong> into new promises without having to take care of ordering of the underlying asynchronous operations yourself.</p><pre>let doSmth = new Promise(resolve =&gt; {<br>    resolve(&#39;doSmth&#39;);<br>  }),<br>  doSmthElse = new Promise(resolve =&gt; {<br>    resolve(&#39;doSmthElse&#39;);<br>  }),<br>  oneMore = new Promise(resolve =&gt; {<br>    resolve(&#39;oneMore&#39;); <br>  });</pre><pre>Promise.<strong>all</strong>([<br>    doSmth,<br>    doSmthElse,<br>    oneMore<br>  ])<br>  .then(response =&gt; {<br>    let [one, two, three] = response;<br>    console.log(one, two, three); // doSmth doSmthElse oneMore<br>  });</pre><p><strong>Promise.all()</strong> takes an array of promises and when all of them are fulfilled, it put their values into the array.</p><p>There are two more functions which are useful:</p><ul><li><strong>Promise.resolve(value)</strong> — it returns a promise which resolves to a <strong>value</strong> or returns <strong>value</strong> if <strong>value</strong> is already a promise</li><li><strong>Promise.reject(value)</strong> —returns rejected promise with <strong>value</strong> as <strong>value</strong></li></ul><h4>Pitfall</h4><p>Promises have its pitfall as well. Let’s image that when any exception is thrown within a <strong>then</strong> or the function passed to <strong>new Promise</strong>, will be silently disposed of <strong>unless manually handled</strong>.</p><p>Next</p><p><a href="https://medium.com/p/a2aeb7e2d384"></a></p><blockquote>Like it? <strong>Recommend it!</strong></blockquote><p><a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a></p><blockquote>Whole series is also available as an <strong>ebook</strong>. I published it on <a href="http://leanpub.com">leanpub.com</a></blockquote><p><a href="https://leanpub.com/ecmascript2015es6guide">ECMAScript 2015 guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbGHEO5gdr_MVNiYQLvK9A.jpeg" /></figure><p>Future is bright!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ca8d8b4aca6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ecmascript-2015/es6-promises-9ca8d8b4aca6">ES6 — promises</a> was originally published in <a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 — modules]]></title>
            <link>https://medium.com/ecmascript-2015/es6-modules-d5646d1b9a08?source=rss----c8958ce340e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/d5646d1b9a08</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[modules]]></category>
            <dc:creator><![CDATA[Maciej Rzepiński]]></dc:creator>
            <pubDate>Thu, 04 Jun 2015 21:02:44 GMT</pubDate>
            <atom:updated>2015-06-19T05:50:00.880Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*RQFLsbQumE-iNrXzs_Oz8g.jpeg" /></figure><h2>ES6 — modules</h2><h3>Let’s talk about ECMAScript 2015</h3><p>Previous</p><p><a href="https://medium.com/p/607804080906"></a></p><h4>Overview</h4><p>Today we have a couple of ways to create <strong>modules</strong>, export &amp; import them. JavaScript doesn’t have any built-in module loader yet. Upcoming ECMAScript 2015 standard gives us a reason to make people happy. Finally ;)</p><p>We have third party standards: <strong>CommonJS</strong> and <strong>AMD</strong>. The most popular, but, unfortunately, incompatible standards for module loaders.</p><blockquote><strong>CommonJS</strong> is known from <a href="https://nodejs.org/"><strong>Node.js</strong></a>. It’s mostly dedicated for servers and it supports synchronous loading. It also has a compact syntax focused on <strong>export</strong> and <strong>require</strong> keywords.</blockquote><blockquote><strong>AMD</strong> and the most popular implementation - <a href="http://requirejs.org/"><strong>RequireJS</strong></a> are dedicated for browsers. AMD supports asynchronous loading, but has more complicated syntax than CommonJS.</blockquote><p>The goal for ES6 is (was) to mix these two standards and make both user groups happy.</p><p>ES6 gives us an easy syntax and support for asynchronous and configurable module loading.</p><blockquote><strong>Async model</strong> — no code executes until requested modules are available and processed.</blockquote><h4>Named export</h4><p>Modules can export multiple objects, which could be simple variables or functions.</p><pre><strong>export</strong> function multiply (x, y) {<br>  return x * y;<br>};</pre><p>We can also export a function stored in a variable, but we have to wrap the variable in a set of curly braces.</p><pre>var <strong>multiply</strong> = function (x, y) {<br>  return x * y;<br>};</pre><pre><strong>export</strong> <strong>{</strong> multiply <strong>}</strong>;</pre><p>We can even export many objects and like in the above example — we have to wrap exported statements in a set of curly braces if we use one export keyword.</p><pre><strong>export</strong> hello = &#39;Hello World&#39;;<br><strong>export</strong> function multiply (x, y) {<br>  return x * y;<br>};</pre><pre>// === <strong>OR</strong> ===</pre><pre>var hello = &#39;Hello World&#39;,<br>    multiply = function (x, y) {<br>      return x * y;<br>    };</pre><pre><strong>export</strong> <strong>{</strong> hello, multiply <strong>}</strong>;</pre><p>Let’s just imagine that we have <strong>modules.js</strong> file with all exported statements. To import them in another file (<strong>in the same directory</strong>) we use … <strong>import</strong> { .. } <strong>from </strong>.. syntax:</p><pre><strong>import</strong> <strong>{</strong> hello <strong>}</strong> <strong>from</strong> &#39;modules&#39;;</pre><blockquote>We can omit <strong>.js</strong> extension just like in CommonJS and AMD.</blockquote><p>We can even import many statements:</p><pre><strong>import</strong> <strong>{</strong> hello, multiply <strong>}</strong> <strong>from</strong> &#39;modules&#39;;</pre><p>Imports may also be <strong>aliased</strong>:</p><pre>import { multiply <strong>as</strong> pow2 } from &#39;modules&#39;;</pre><p>.. and use <strong>wildcard (*)</strong> to import all exported statemets:</p><pre>import <strong>*</strong> from &#39;modules&#39;;</pre><h4>Default export</h4><p>In our module, we can have many named exports, but we can also have a <strong>default export</strong>. It’s because our module could be a large library and with default export we can import then an entire module. It could be also useful when our module has single value or model (class / constructor).</p><blockquote><strong>One</strong> default export <strong>per</strong> <strong>module</strong>.</blockquote><pre>export <strong>default</strong> function (x, y) {<br>  return x * y;<br>};</pre><p>This time we don’t have to use curly braces for importing and we have a chance to name imported statement as we wish.</p><pre>import multiply from &#39;modules&#39;;</pre><pre>// === OR ===</pre><pre>import pow2 from &#39;modules&#39;;</pre><pre>// === OR ===</pre><pre>...</pre><blockquote>Module can have <strong>both</strong> named exports and a default export.</blockquote><pre>// modules.js<br>export hello = &#39;Hello World&#39;;<br>export <strong>default</strong> function (x, y) {<br>  return x * y;<br>};</pre><pre>// app.js<br>import pow2, { hello } from &#39;modules&#39;;</pre><blockquote>The <strong>default export</strong> is just a <strong>named export</strong> with the special name <strong>default</strong>.</blockquote><pre>// modules.js<br>export default function (x, y) {<br>  return x * y;<br>};</pre><pre>// app.js<br>import { <strong>default</strong> } from &#39;modules&#39;;</pre><h4>API</h4><p>In addition, there is also a programmatic API and it allows to:</p><ul><li>Programmatically work with modules and scripts</li><li>Configure module loading</li></ul><blockquote><a href="https://github.com/systemjs/systemjs"><strong>SystemJS</strong></a> — universal dynamic module loader — loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS. Works with both <strong>Traceur</strong> and <strong>Babel</strong>.</blockquote><p>Module loader should support:</p><ul><li>Dynamic loading</li><li>Global namespace isolation</li><li>Nested virtualization</li><li>Compilation hooks</li></ul><p>Next</p><p><a href="https://medium.com/p/9ca8d8b4aca6"></a></p><blockquote><em>Like it? </em><strong><em>Recommend it!</em></strong></blockquote><p><a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a></p><blockquote>Whole series is also available as an <strong>ebook</strong>. I published it on <a href="http://leanpub.com">leanpub.com</a></blockquote><p><a href="https://leanpub.com/ecmascript2015es6guide">ECMAScript 2015 guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbGHEO5gdr_MVNiYQLvK9A.jpeg" /></figure><p>Future is bright!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5646d1b9a08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ecmascript-2015/es6-modules-d5646d1b9a08">ES6 — modules</a> was originally published in <a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 — classes and inheritance]]></title>
            <link>https://medium.com/ecmascript-2015/es6-classes-and-inheritance-607804080906?source=rss----c8958ce340e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/607804080906</guid>
            <category><![CDATA[class]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Maciej Rzepiński]]></dc:creator>
            <pubDate>Thu, 04 Jun 2015 21:02:39 GMT</pubDate>
            <atom:updated>2015-06-19T05:49:43.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*RQFLsbQumE-iNrXzs_Oz8g.jpeg" /></figure><h2>ES6 — classes and inheritance</h2><h3>Let’s talk about ECMAScript 2015</h3><p>Previous</p><p><a href="https://medium.com/p/4494aa135ad3"></a></p><p><strong>OO</strong> keywords is probably the most awaited features in ES6. <strong>Classes</strong> are something like another syntactic sugar over the prototype-based OO pattern. We now have one, concise way to make class patterns easier to use.</p><blockquote>Over the prototype-based <strong>OO pattern</strong> to ensure <strong>backwards compatibility</strong>.</blockquote><h4>Overview — an example of ES6 class syntax and ES5 equivalent</h4><pre><strong>class</strong> Vehicle {<br> <br>  <strong>constructor</strong> (name, type) {<br>    this.name = name;<br>    this.type = type;<br>  }<br> <br>  getName () {<br>    return this.name;<br>  }<br> <br>  getType () {<br>    return this.type;<br>  }<br> <br>}</pre><pre>let car = new Vehicle(&#39;Tesla&#39;, &#39;car&#39;);<br>console.log(car.getName()); // Tesla<br>console.log(car.getType()); // car</pre><p>It’s naive example, but we can see a new keywords as <strong>class </strong>and <strong>constructor</strong>.</p><p>ES5 equivalent could be something like this:</p><pre>function Vehicle (name, type) {<br>  this.name = name;<br>  this.type = type;<br>};<br> <br>Vehicle.prototype.getName = function getName () {<br>  return this.name;<br>};<br> <br>Vehicle.prototype.getType = function getType () {<br>  return this.type;<br>};</pre><pre>var car = new Vehicle(&#39;Tesla&#39;, &#39;car&#39;);<br>console.log(car.getName()); // Tesla<br>console.log(car.getType()); // car</pre><blockquote>Classes support prototype-based <strong>inheritance</strong>, <strong>super calls</strong>, <strong>instance</strong> and <strong>static methods</strong> and <strong>constructors</strong>.</blockquote><p>It’s simple. We instantiate our classes the same way, but let’s add some..</p><h4>inheritance</h4><p>..to it and start from ES5 example:</p><pre>function Vehicle (name, type) {<br>  this.name = name;<br>  this.type = type;<br>};<br> <br>Vehicle.prototype.getName = function getName () {<br>  return this.name;<br>};<br> <br>Vehicle.prototype.getType = function getType () {<br>  return this.type;<br>};</pre><pre>function Car (name) {<br>  Vehicle.call(this, name, ‘car’);<br>}</pre><pre>Car.prototype = Object.create(Vehicle.prototype);<br>Car.prototype.constructor = Car;<br>Car.parent = Vehicle.prototype;<br>Car.prototype.getName = function () {<br>  return &#39;It is a car: &#39;+ this.name;<br>};</pre><pre>var car = new Car(&#39;Tesla&#39;);<br>console.log(car.getName()); // It is a car: Tesla<br>console.log(car.getType()); // car</pre><p>And now look at the ES6 version:</p><pre>class Vehicle {<br> <br>  constructor (name, type) {<br>    this.name = name;<br>    this.type = type;<br>  }<br> <br>  getName () {<br>    return this.name;<br>  }<br> <br>  getType () {<br>    return this.type;<br>  }<br> <br>}</pre><pre>class Car <strong>extends</strong> Vehicle {<br> <br>  constructor (name) {<br>    <strong>super</strong>(name, &#39;car&#39;);<br>  }<br> <br>  getName () {<br>    return &#39;It is a car: &#39; + <strong>super</strong>.getName();<br>  }<br> <br>}</pre><pre>let car = new Car(&#39;Tesla&#39;);<br>console.log(car.getName()); // It is a car: Tesla<br>console.log(car.getType()); // car</pre><p>We see how easy is to implement inheritance with ES6. It’s finally looking like in other OO programming languages. We use <strong>extends</strong> to inherit from another class and the <strong>super</strong> keyword to call the parent class (function). Moreover, <strong>getName()</strong> method was overridden in subclass <strong>Car</strong>.</p><blockquote><strong>super</strong> — previously to achieve such functionality in Javascript required the use of <strong>call</strong> or <strong>apply</strong></blockquote><h4>static</h4><pre>class Vehicle {<br> <br>  constructor (name, type) {<br>    this.name = name;<br>    this.type = type;<br>  }<br> <br>  getName () {<br>    return this.name;<br>  }<br> <br>  getType () {<br>    return this.type;<br>  }<br> <br>  <strong>static</strong> create (name, type) {<br>    return new Vehicle(name, type);<br>  }<br> <br>}</pre><pre>let car = Vehicle.create(&#39;Tesla&#39;, &#39;car&#39;);<br>console.log(car.getName()); // Tesla<br>console.log(car.getType()); // car</pre><p>Classes gives us an opportunity to create static members. We don’t have to use the <strong>new</strong> keyword later to instantiate a class.</p><blockquote><strong>static</strong> methods (properties) are also inherited<br>and could be called by <strong>super</strong></blockquote><h4>get / set</h4><p>Other great things in upcoming ES6 are <strong>getters</strong> and <strong>setters</strong> for object properties. They allow us to run the code on the reading or writing of a property.</p><pre>class Car {<br> <br>  constructor (name) {<br>    this._name = name;<br>  } <br> <br>  <strong>set</strong> name (name) {<br>    this._name = name;<br>  }<br> <br>  <strong>get</strong> name () {<br>    return this._name;<br>  }<br> <br>}</pre><pre>let car = new Car(&#39;Tesla&#39;);<br>console.log(car.name); // Tesla</pre><pre>car.name = &#39;BMW&#39;;<br>console.log(car.name); // BMW</pre><p>I use ‘<strong>_</strong>’ prefix to create a (<strong>tmp</strong>) field to store name property.</p><h4>Enhanced Object Properties</h4><p>The last thing I have to mention is <strong>property shorthand</strong>, <strong>computed property names</strong> and <strong>method properties</strong>.</p><p>ES6 gives us shorter syntax for common <strong>object property</strong> definition:</p><pre>// <strong>ES6</strong><br>let x = 1,<br>    y = 2,<br>    obj = { <strong>x</strong>, <strong>y</strong> };</pre><pre>console.log(obj); // Object { x: 1, y: 2 }</pre><pre>// <strong>ES5</strong><br>var x = 1,<br>    y = 2,<br>    obj = {<br>      <strong>x: x,<br>      y: y</strong><br>    };</pre><pre>console.log(obj); // Object { x: 1, y: 2 }</pre><p>As you can see, this works because the property value has the same name as the property identifier.</p><p>Another thing is ES6 support for <strong>computed names</strong> in object property definitions:</p><pre>// <strong>ES6</strong><br>let getKey = () =&gt; &#39;123&#39;,<br>    obj = {<br>      foo: &#39;bar&#39;,<br>      [<strong>&#39;key_&#39; + getKey()</strong>]: 123<br>    };</pre><pre>console.log(obj); // Object { foo: &#39;bar&#39;, key_123: 123 }</pre><pre>// <strong>ES5<br></strong>var getKey = function () {<br>      return &#39;123&#39;;<br>    },<br>    obj = {<br>      foo: &#39;bar&#39;<br>    };</pre><pre>obj[<strong>&#39;key_&#39; + getKey()</strong>] = 123;</pre><pre>console.log(obj); // Object { foo: &#39;bar&#39;, key_123: 123 }</pre><p>The one last thing is <strong>method properties</strong> seen in classes above. We can even use it in object definitions:</p><pre>// <strong>ES6</strong><br>let obj = {<br>  name: &#39;object name&#39;,<br>  <strong>toString</strong> () { // &#39;<strong>function</strong>&#39; keyword is omitted here<br>    return this.name;<br>  }<br>};</pre><pre>console.log(obj.toString()); // object name</pre><pre>// <strong>ES5<br></strong>var obj = {<br>  name: &#39;object name&#39;,<br>  <strong>toString</strong>: <strong>function</strong> () {<br>    return this.name;<br>  }<br>};</pre><pre>console.log(obj.toString()); // object name</pre><p>Next</p><p><a href="https://medium.com/p/d5646d1b9a08"></a></p><blockquote><em>Like it? </em><strong><em>Recommend it!</em></strong></blockquote><p><a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a></p><blockquote>Whole series is also available as an <strong>ebook</strong>. I published it on <a href="http://leanpub.com">leanpub.com</a></blockquote><p><a href="https://leanpub.com/ecmascript2015es6guide">ECMAScript 2015 guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbGHEO5gdr_MVNiYQLvK9A.jpeg" /></figure><p>Future is bright!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=607804080906" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ecmascript-2015/es6-classes-and-inheritance-607804080906">ES6 — classes and inheritance</a> was originally published in <a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 — generators]]></title>
            <link>https://medium.com/ecmascript-2015/es6-generators-4494aa135ad3?source=rss----c8958ce340e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/4494aa135ad3</guid>
            <category><![CDATA[generator]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Maciej Rzepiński]]></dc:creator>
            <pubDate>Thu, 04 Jun 2015 21:02:35 GMT</pubDate>
            <atom:updated>2015-06-19T05:49:27.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*RQFLsbQumE-iNrXzs_Oz8g.jpeg" /></figure><h3>Let’s talk about ECMAScript 2015</h3><p>Previous</p><p><a href="https://medium.com/p/4afec026f70a"></a></p><p><strong>Generators</strong> are simply subtypes of <strong>Iterators</strong> which I wrote about previously. They are a special kind of function that can be suspended and resumed, which is making a difference to iterators. Generators use <strong>function*</strong> and <strong>yield</strong> operators to work their magic.</p><blockquote>The <strong>yield </strong>operator returns a value from the function and when the generator is resumed, execution continues <strong>after the yield</strong>.</blockquote><blockquote>We also have to use <strong>function*</strong> (with star character) instead of a function to return a generator instance.</blockquote><blockquote>!!! Generators have been borrowed from Python language.</blockquote><blockquote>The most magical feature in ES6!</blockquote><p>Why? Take a look:</p><pre><strong>function*</strong> generator () {<br>  <strong>yield</strong> 1; <br>  // pause<br>  <strong>yield</strong> 2; <br>  // pause<br>  <strong>yield</strong> 3; <br>  // pause<br>  <strong>yield</strong> &#39;done?&#39;; <br>  // done<br>}</pre><pre>let gen = generator(); // [object <strong>Generator</strong>]</pre><pre>console.log(gen.<strong>next</strong>()); // Object {value: <strong>1</strong>, done: false}<br>console.log(gen.<strong>next</strong>()); // Object {value: <strong>2</strong>, done: false}<br>console.log(gen.<strong>next</strong>()); // Object {value: <strong>3</strong>, done: false}<br>console.log(gen.<strong>next</strong>()); // Object {value: <strong>&#39;done?&#39;</strong>, done: false}</pre><pre>console.log(gen.<strong>next</strong>()); // Object {value: <strong>undefined</strong>, done: true}<br>console.log(gen.<strong>next</strong>()); // Object {value: <strong>undefined</strong>, done: true}</pre><pre><strong>for</strong> (let val <strong>of</strong> generator()) {<br>  console.log(val); // 1<br>                    // 2<br>                    // 3<br>                    // &#39;done?&#39;<br>}</pre><p>As you can see, the generator has four <strong>yield</strong> statements. Each returns a value, pauses execution and moves to the next yield when <strong>next()</strong> method is called. Calling a function produces an object for controlling generator execution, a so-called <strong>generator object</strong>.</p><p>Use is similar to iterators. We have <strong>next()</strong> method as I mentioned above and we can even use it with <strong>for-of</strong> loop.</p><p>Below is an example of a generator called <strong>random1_10</strong>, which returns random numbers from 1 to 10.</p><pre>function* random1_10 () {<br>  while (true) {<br>    <strong>yield</strong> Math.floor(Math.random() * 10) + 1;<br>  }<br>}</pre><pre>let rand = random1_10();<br>console.log(rand.<strong>next</strong>());<br>console.log(rand.<strong>next</strong>());</pre><pre>// …</pre><p>Generator has never ending <strong>while</strong> loop. It produces random numbers every time when you call <strong>next()</strong> method.</p><p>ES5 implementation:</p><pre>function random1_10 () {<br>  return {<br>    <strong>next</strong>: function() {<br>      return {<br>        value: Math.floor(Math.random() * 10) + 1,<br>        done: false<br>      };<br>    }<br>  };<br>}</pre><pre>let rand = random1_10();<br>console.log(rand.next());<br>console.log(rand.next());</pre><pre>// …</pre><p>We can also mix generators together:</p><pre>function* random (max) {<br>  yield Math.floor(Math.random() * max) + 1;<br>}</pre><pre>function* random1_20 () {<br>  while (true) {<br>    yield* <strong>random</strong>(20);<br>  }<br>}</pre><pre>let rand = random1_20();<br>console.log(rand.next());<br>console.log(rand.next());</pre><pre>// …</pre><p><strong>random1_20</strong> generator returns random values from 1 to 20. It uses <strong>random</strong> generator inside to create random number each time when yield statement is reached.</p><p>Next</p><p><a href="https://medium.com/p/607804080906"></a></p><blockquote><em>Like it? </em><strong><em>Recommend it!</em></strong></blockquote><p><a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a></p><blockquote>Whole series is also available as an <strong>ebook</strong>. I published it on <a href="http://leanpub.com">leanpub.com</a></blockquote><p><a href="https://leanpub.com/ecmascript2015es6guide">ECMAScript 2015 guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbGHEO5gdr_MVNiYQLvK9A.jpeg" /></figure><p>Future is bright!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4494aa135ad3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ecmascript-2015/es6-generators-4494aa135ad3">ES6 — generators</a> was originally published in <a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 — iterators]]></title>
            <link>https://medium.com/ecmascript-2015/es6-iterators-4afec026f70a?source=rss----c8958ce340e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/4afec026f70a</guid>
            <category><![CDATA[iterators]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maciej Rzepiński]]></dc:creator>
            <pubDate>Thu, 04 Jun 2015 21:02:30 GMT</pubDate>
            <atom:updated>2015-06-19T05:49:08.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*RQFLsbQumE-iNrXzs_Oz8g.jpeg" /></figure><h3>Let’s talk about ECMAScript 2015</h3><p>Previous</p><p><a href="https://medium.com/p/bae03d964d43"></a></p><h4>iterator &amp; iterable</h4><blockquote>An <strong>iterator</strong> is an object with a <strong>next</strong> method that returns <strong>{ done, value }</strong> tuples.</blockquote><p>ES6 gives us a pattern for creating custom iterators and it has a similar implementation to Java <strong>Iterable</strong> or .NET <strong>IEnumerable</strong>. It has also built-in <strong>iterables</strong>: <strong>String</strong>, <strong>Array</strong>, <strong>TypedArray</strong>, <strong>Map</strong> and <strong>Set</strong>. An iterator object can be any object with a <strong>next()</strong> method.</p><blockquote><strong>Iterable</strong> is an object which has <strong>[Symbol.iterator]()</strong> method inside.</blockquote><blockquote><strong>Symbol</strong> is in turn an unique and immutable data type which can be used as an identifier for <strong>object properties</strong> — no equivalent in ES5.</blockquote><pre>// Symbol<br>let s1 = <strong>Symbol</strong>(&#39;abc&#39;);<br>let s2 = <strong>Symbol</strong>(&#39;abc&#39;);<br>console.log(s1 !== s2); // <strong>true</strong><br>console.log(typeof s1); // <strong>&#39;symbol&#39;</strong><br>let obj = {};<br>obj[s1] = &#39;abc&#39;;<br>console.log(obj); // <strong>Object { Symbol(abc): &#39;abc&#39; }</strong></pre><p>Let’s see a simple iterator written from scratch, which allows us to iterate through random numbers which are dynamically generated by <strong>next()</strong> method. A function returning iterable object take one argument (<strong>items</strong>) which is used to determine if the iterator should stop and returns <strong>done = true</strong>.</p><pre>let random1_10 = function (items = 1) {<br>  return {<br>    <strong>[Symbol.iterator]()</strong> {<br>      let cur = 0;<br>      return {<br>        <strong>next()</strong> {<br>          let done = cur === items,<br>              random = Math.floor(Math.random() * 10) + 1;<br>          ++cur;<br>          return {<br>            done: done,<br>            value: random<br>          }<br>        }<br>      }<br>    }<br>  };<br>};</pre><pre>for (let n of random1_10(5)) {<br>  console.log(n); // prints 5 random numbers<br>}</pre><p>Every time <strong>for-of</strong> loop call <strong>next()</strong> method, an iterator generate a random number and returns it to the loop.</p><blockquote>If the iterator returns <strong>done = true</strong>, you can omit value, so the result will be<br><strong>{ done: true }</strong></blockquote><pre>let random1_10 = function (items = 1) {<br>  return {<br>    [Symbol.iterator]() {<br>      let cur = 0;<br>      return {<br>        next() {<br>          if (cur === items) {<br>            <strong>return {<br>              done: true <br>            }</strong><br>          }</pre><pre>          ++cur;<br>          return {<br>            done: false,<br>            value: Math.floor(Math.random() * 10) + 1<br>          }<br>        }<br>      }<br>    }<br>  };<br>};</pre><pre>for (let n of random1_10(5)) {<br> console.log(n); // prints 5 random numbers<br>}</pre><h4>for-of loop</h4><p>ES6 has a new loop — <strong>for-of</strong>. It works with iterables. Let’s look at his signature:</p><pre>for (LET of ITERABLE) {<br>  CODE BLOCK<br>}</pre><p>It’s similar to <strong>for-in</strong> loop, which can be used to iterate through object properties (plain old Objects).</p><p><strong>Arrays</strong> in ES6 are iterable by default, so we finally can use <strong>for-of</strong> for looping over the elements.</p><pre>const arr = [1, 2, 3, 4, 5];</pre><pre><strong>for</strong> (let item <strong>of</strong> arr) {<br>  console.log(item); // 1<br>                     // 2<br>                     // 3<br>                     // 4<br>                     // 5<br>}</pre><p>Inside the for-of loop, we can even use a <strong>break</strong>, <strong>continue</strong> and <strong>return</strong>.</p><pre>const arr = [1, 2, 3, 4, 5];</pre><pre>for (let item of arr) {<br>  if (item &gt; 4) {<br>    <strong>break</strong>;<br>  }<br>  if (0 !== item % 2) {<br>    <strong>continue</strong>;<br>  }<br>  console.log(item); // 2<br>                     // 4<br>}</pre><p>Next</p><p><a href="https://medium.com/p/4494aa135ad3"></a></p><blockquote><em>Like it? </em><strong><em>Recommend it!</em></strong></blockquote><p><a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a></p><blockquote>Whole series is also available as an <strong>ebook</strong>. I published it on <a href="http://leanpub.com">leanpub.com</a></blockquote><p><a href="https://leanpub.com/ecmascript2015es6guide">ECMAScript 2015 guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbGHEO5gdr_MVNiYQLvK9A.jpeg" /></figure><p>Future is bright!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4afec026f70a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ecmascript-2015/es6-iterators-4afec026f70a">ES6 — iterators</a> was originally published in <a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 — strings]]></title>
            <link>https://medium.com/ecmascript-2015/es6-string-bae03d964d43?source=rss----c8958ce340e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/bae03d964d43</guid>
            <category><![CDATA[string]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Maciej Rzepiński]]></dc:creator>
            <pubDate>Thu, 04 Jun 2015 21:02:26 GMT</pubDate>
            <atom:updated>2015-06-19T05:48:50.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*RQFLsbQumE-iNrXzs_Oz8g.jpeg" /></figure><h2>ES6 — strings</h2><h3>Let’s talk about ECMAScript 2015</h3><p>Previous</p><p><a href="https://medium.com/p/13ca399f993a"></a></p><p>Hello in “Let’s talk about ECMAScript 2015” series. Today I gonna show you a couple of changes to <strong>strings</strong> in JavaScript, which will be available when ES6 comes. A syntactic sugar, which could be helpful in daily work.</p><h4>template strings</h4><p>First, a <strong>string interpolation</strong>. Yep, template strings (finally) support string interpolation. ES6 brings us also support for <strong>multi-line</strong> syntax and <strong>raw literals</strong>.</p><pre>let x = 1;<br>let y = 2;<br>let sumTpl = `${x} + ${y} = ${x + y}`;<br> <br>console.log(sumTpl); // 1 + 2 = 3</pre><p>As you can see, we can inject values to string by using <strong>${value}</strong> syntax. Another thing to consider is <strong>grave accent</strong> — a char under the tilde (~) on a keyboard. A template literal string must be wrapped by it, to work properly.</p><p>The example above is an equivalent (in ES5) to simply (Babel version):</p><pre>var x = 1;<br>var y = 2;<br>var sumTpl = &quot;&quot; + x + &quot; + &quot; + y + &quot; = &quot; + (x + y);</pre><pre>console.log(sumTpl); // 1 + 2 = 3</pre><p>This feature is very useful and almost removes the need for a template system.</p><p>Template strings provide also <strong>multi-line syntax</strong>, which is not legal in ES5 and earlier.</p><pre>let types = `Number<br>String<br>Array<br>Object`;</pre><pre>console.log(types); // Number<br>                    // String<br>                    // Array<br>                    // Object</pre><p>ES5 equivalent:</p><pre>var types = &quot;Number\nString\nArray\nObject&quot;;</pre><pre>console.log(types); // Number<br>                    // String<br>                    // Array<br>                    // Object</pre><p>The last thing is access the <strong>raw template string</strong> content where backslashes are not interpreted. We don’t have equivalent in ES5 here.</p><pre>let interpreted = &#39;raw\nstring&#39;;<br>let esaped = &#39;raw\\nstring&#39;;<br>let raw = String.raw`raw\nstring`;</pre><pre>console.log(interpreted);    // raw<br>                             // string<br>console.log(raw === esaped); // true</pre><h4>extended support for Unicode</h4><p>ES6 gives us full support for <strong>Unicode</strong> within strings and regular expressions. It’s non-breaking addition allows to building global apps.</p><p>Let’s see an example:</p><pre>let str = &#39;𠮷&#39;;</pre><pre>console.log(str.length);             // 2<br>console.log(str === &#39;\uD842\uDFB7&#39;); // true</pre><p>You can see that character <strong>𠮷</strong> is represented by two 16-bit code units. It’s a surrogate pair in which we have a single code point represented by two code units. The length of that string is also 2.</p><blockquote><em>Surrogate pairs are used in UTF-16 to represent code points above U+FFFF.</em></blockquote><pre>console.log(str.charCodeAt(0)); // 55362<br>console.log(str.charCodeAt(1)); // 57271</pre><p>The <strong>charCodeAt()</strong> method returns the 16-bit number for each code unit.</p><p>ES6 allows encoding of strings in UTF-16. JavaScript can now support work with surrogate pairs. It gives us also a new method <strong>codePointAt()</strong> that returns Unicode code point instead of Unicode code unit.</p><pre>console.log(str.codePointAt(0)); // 134071<br>console.log(str.codePointAt(1)); // 57271</pre><pre>console.log(str.codePointAt(0) === 0x20BB7); // true</pre><p>It works the same as <strong>charCodeAt()</strong> except for non-BMP characters.</p><blockquote><strong>BMP</strong> — Basic Multilingual Plane — the first 2^16 code points.</blockquote><p><strong>codePointAt()</strong> returns full code point at the <strong>0 position</strong>. codePointAt() and charCodeAt() return the same value for <strong>position 1</strong>.</p><p>We can also do a reverse operation with another new method added to ES6: <strong>fromCodePoint()</strong>.</p><pre>console.log(String.fromCodePoint(134071));  // &quot;𠮷&quot;<br>console.log(String.fromCodePoint(0x20BB7)); // &quot;𠮷&quot;</pre><blockquote>Unicode code unit escape sequences consist of six characters, namely <strong>\u</strong> plus four hexadecimal digits, and contribute one code unit.</blockquote><blockquote>Unicode code point escape sequences consist of five to ten characters, namely<br><strong>\u{ 1–6 hexadecimal digits }</strong>, and contribute one or two code units.</blockquote><p>Dealing with that two definitions, above example could be represented by one code point in <strong>ES6</strong>:</p><pre>// ES6 way<br>console.log(&#39;\u{20BB7}&#39;); // 𠮷<br>console.log(&#39;\u{20BB7}&#39; === &#39;\uD842\uDFB7&#39;); // true</pre><pre>// ES5 way<br>console.log(&#39;\u20BB7); // 7!<br>console.log(&#39;\u20BB7&#39; === &#39;\uD842\uDFB7&#39;); // false</pre><p>In ES5 we get an unexpected result when we try to match one single character using regular expression.</p><pre>console.log(/^.$/.test(str)); // false - length is 2</pre><p>ES6 allows us to use new RegExp <strong>u mode</strong> to handle code points. It is simply a new <strong>u </strong>flag (u == Unicode).</p><pre>console.log(/^.$/u.test(str)); // true</pre><p>Adding u flag allows to correctly match the string by characters instead of code units.</p><h4>strings are iterable</h4><p>Strings are iterable by using the <strong>for-of</strong> loop which I will cover in more detail in iterators article later. I write about it now because it enumerate Unicode code points and each may comprise one or two characters.</p><pre>let str = &#39;abc\uD842\uDFB7&#39;;</pre><pre>console.log(str.length); // 5</pre><pre>for (let c of str) {<br>  console.log(c); // a<br>                  // b<br>                  // c<br>                  // 𠮷<br>}</pre><p>We can also use <strong>spread</strong> operator to transform string into an array with full Unicode support.</p><pre>let str = &#39;abc\uD842\uDFB7&#39;;<br>let chars = […str];</pre><pre>console.log(chars); // [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;𠮷&#39;]</pre><h4>new string methods</h4><p><strong>repeat(n) </strong>— string repeats by <strong>n</strong> times</p><pre>console.log(&#39;abc|&#39;.repeat(3)); // &#39;abc|abc|abc|&#39;</pre><p><strong>startsWith(str, starts = 0) : boolean</strong> — check if string starts with <strong>str</strong>, starting from <strong>starts</strong></p><pre>console.log(&#39;ecmascript&#39;.startsWith(&#39;ecma&#39;));      // true<br>console.log(&#39;ecmascript&#39;.startsWith(&#39;script&#39;, 4)); // true</pre><p><strong>endsWith(str, ends = str.length) : boolean </strong>— check if string ends with <strong>str</strong>, <strong>ends</strong> — where the string to be checked ends</p><pre>console.log(&#39;ecmascript&#39;.endsWith(&#39;script&#39;));  // true<br>console.log(&#39;ecmascript&#39;.endsWith(&#39;ecma&#39;, 4)); // true</pre><p><strong>includes(str, starts = 0) : boolean</strong> — check if string contain <strong>str</strong>, starting from <strong>starts</strong></p><pre>console.log(&#39;ecmascript&#39;.includes(&#39;ecma&#39;));      // true<br>console.log(&#39;ecmascript&#39;.includes(&#39;script&#39;, 4)); // true</pre><p>Next</p><p><a href="https://medium.com/p/4afec026f70a"></a></p><blockquote><em>Like it? </em><strong><em>Recommend it!</em></strong></blockquote><p><a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a></p><blockquote>Whole series is also available as an <strong>ebook</strong>. I published it on <a href="http://leanpub.com">leanpub.com</a></blockquote><p><a href="https://leanpub.com/ecmascript2015es6guide">ECMAScript 2015 guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbGHEO5gdr_MVNiYQLvK9A.jpeg" /></figure><p>Future is bright!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bae03d964d43" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ecmascript-2015/es6-string-bae03d964d43">ES6 — strings</a> was originally published in <a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 — destructuring]]></title>
            <link>https://medium.com/ecmascript-2015/es6-destructuring-13ca399f993a?source=rss----c8958ce340e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/13ca399f993a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[destructuring]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Maciej Rzepiński]]></dc:creator>
            <pubDate>Thu, 04 Jun 2015 21:02:21 GMT</pubDate>
            <atom:updated>2015-06-19T05:48:32.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*RQFLsbQumE-iNrXzs_Oz8g.jpeg" /></figure><h2>ES6 — destructuring</h2><h3>Let’s talk about ECMAScript 2015</h3><p>Previous</p><p><a href="https://medium.com/p/f3ab0d2e0a5e"></a></p><p><strong>Destructuring</strong> is one more little addition to the upcoming JavaScript standard, which helps us write code more flexibly and effectively.</p><p>It allows binding using pattern matching. We can use it for matching arrays and objects. It’s similar to standard object look up and returns <strong>undefined </strong>when value is not found.</p><h4>arrays</h4><p>Today it’s common to see the code such as this.</p><pre>// ES5</pre><pre>var point = [1, 2];</pre><pre>var xVal = point[0],<br>    yVal = point[1];<br> <br>console.log(xVal); // 1<br>console.log(yVal); // 2</pre><p>ES6 gives us destructuring of arrays into individual variables during assignment which is intuitive and flexible.</p><pre>// ES6</pre><pre>let point = [1, 2];<br>let [xVal, yVal] = point;<br> <br>console.log(xVal); // 1<br>console.log(yVal); // 2</pre><pre>// .. and reverse!<br>[xVal, yVal] = [yVal, xVal];<br> <br>console.log(xVal); // 2<br>console.log(yVal); // 1</pre><p>We can even omit some values..</p><pre>let threeD = [1, 2, 3];</pre><pre>let [a, , c] = threeD;</pre><pre>console.log(a); // 1<br>console.log(c); // 3</pre><p>..and have nested array destructuring.</p><pre>let nested = [1, [2, 3], 4];</pre><pre>let [a, [b], d] = nested;</pre><pre>console.log(a); // 1<br>console.log(b); // 2<br>console.log(d); // 4</pre><h4>objects</h4><p>As well as the array syntax, ES6 also has the ability to destructure objects. It uses an object literal on the left side of an assignment operation. Object pattern is very similar to array pattern seen above. Let’s see:</p><pre>let point = {<br>  x: 1,<br>  y: 2<br>};</pre><pre>let { x: a, y: b } = point;</pre><pre>console.log(a); // 1<br>console.log(b); // 2</pre><p>It supports nested object as well as array pattern.</p><pre>let point = {<br>  x: 1,<br>  y: 2,<br>  z: {<br>    one: 3,<br>    two: 4<br>  }<br>};</pre><pre>let { x: a, y: b, z: { one: c, two: d } } = point;</pre><pre>console.log(a); // 1<br>console.log(b); // 2<br>console.log(c); // 3<br>console.log(d); // 4</pre><h4>mixed</h4><p>We can also mix objects and arrays together and use theirs literals.</p><pre>let mixed = {<br>  one: 1,<br>  two: 2,<br>  values: [3, 4, 5]<br>};</pre><pre>let { one: a, two: b, values: [c, , e] } = mixed;</pre><pre>console.log(a); // 1<br>console.log(b); // 2<br>console.log(c); // 3<br>console.log(e); // 5</pre><p>But I think the most interesting is that we are able to use <strong>functions</strong> which return destructuring assignment.</p><pre>function mixed () {<br>  return {<br>    one: 1,<br>    two: 2,<br>    values: [3, 4, 5]<br>  };<br>}</pre><pre>let { one: a, two: b, values: [c, , e] } = mixed();</pre><pre>console.log(a); // 1<br>console.log(b); // 2<br>console.log(c); // 3<br>console.log(e); // 5</pre><p>The same result! It gives us a lot of possibilities to use it in our code.</p><h4>attention!</h4><blockquote>If the value of a destructuring assignment isn’t match, it evaluates to undefined.</blockquote><pre>let point = {<br>  x: 1<br>};</pre><pre>let { x: a, y: b } = point;</pre><pre>console.log(a); // 1<br>console.log(b); // undefined</pre><blockquote>If we try to omit <strong>var</strong>, <strong>let</strong> or <strong>const</strong>, it will throw an error, because block code can‘t be destructuring assignment.</blockquote><pre>let point = {<br>  x: 1<br>};</pre><pre>{ x: a } = point; // throws error</pre><p>We have to wrap it in parentheses. Just that ☺</p><pre>let point = {<br>  x: 1<br>};</pre><pre>({ x: a } = point);</pre><pre>console.log(a); // 1</pre><p>Next</p><p><a href="https://medium.com/p/bae03d964d43"></a></p><blockquote><em>Like it? </em><strong><em>Recommend it!</em></strong></blockquote><p><a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a></p><blockquote>Whole series is also available as an <strong>ebook</strong>. I published it on <a href="http://leanpub.com">leanpub.com</a></blockquote><p><a href="https://leanpub.com/ecmascript2015es6guide">ECMAScript 2015 guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbGHEO5gdr_MVNiYQLvK9A.jpeg" /></figure><p>Future is bright!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13ca399f993a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ecmascript-2015/es6-destructuring-13ca399f993a">ES6 — destructuring</a> was originally published in <a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 — default + rest + spread]]></title>
            <link>https://medium.com/ecmascript-2015/default-rest-spread-f3ab0d2e0a5e?source=rss----c8958ce340e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/f3ab0d2e0a5e</guid>
            <category><![CDATA[default]]></category>
            <category><![CDATA[spread]]></category>
            <category><![CDATA[rest]]></category>
            <dc:creator><![CDATA[Maciej Rzepiński]]></dc:creator>
            <pubDate>Thu, 04 Jun 2015 21:02:17 GMT</pubDate>
            <atom:updated>2017-08-01T05:04:51.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*RQFLsbQumE-iNrXzs_Oz8g.jpeg" /></figure><h2>ES6 — default + rest + spread</h2><h3>Let’s talk about ECMAScript 2015</h3><p>Previous</p><p><a href="https://medium.com/p/bb08eeb11667"></a></p><p>ECMAScript 2015 functions made a significant progress, taking into account years of complaints. The result is a number of improvements that make programming in JavaScript <strong>less error-prone</strong> and <strong>more powerful</strong>.</p><p>Let’s see three new features which give us <strong>extended parameter handling</strong>.</p><h4>default</h4><p>It’s a simple, little addition that makes it much easier to handle function parameters. Functions in JavaScript allow any number of parameters to be passed regardless of the number of declared parameters in the function definition. You probably know <strong>commonly seen pattern</strong> in current JavaScript code:</p><pre>function inc(number, increment) {<br>  // set default to 1 if increment not passed<br>  // (or passed as undefined)<br>  increment = increment || 1;</pre><pre>  return number + increment;<br>}</pre><pre>console.log(inc(2, 2)); // 4<br>console.log(inc(2));    // 3</pre><p>The logical <strong>OR operator</strong> (||) always returns the second operand when the first is falsy.</p><p><strong>ES6</strong> gives us a way to set default function parameters. Any parameters with a default value are considered to be optional.</p><p>ES6 version of <strong>inc</strong> function looks like this:</p><pre>function inc(number, increment = 1) {<br>  return number + increment;<br>}</pre><pre>console.log(inc(2, 2)); // 4<br>console.log(inc(2));    // 3</pre><p>You can also set default values to parameters that appear <strong>before arguments</strong> without default values:</p><pre>function sum(a, b = 2, c) {<br>  return a + b + c;<br>}</pre><pre>console.log(sum(1, 5, 10));         // 16 -&gt; b === 5<br>console.log(sum(1, undefined, 10)); // 13 -&gt; b as default</pre><p>You can even execute a function to set default parameter. So it’s not restricted to <strong>primitive values</strong>.</p><pre>function getDefaultIncrement() {<br>  return 1;<br>}</pre><pre>function inc(number, increment = getDefaultIncrement()) {<br>  return number + increment;<br>}</pre><pre>console.log(inc(2, 2)); // 4<br>console.log(inc(2));    // 3</pre><h4>rest</h4><p>Let’s rewrite <strong>sum</strong> function to handle all arguments passed to it (without validation — just to be clear). If we want to use <strong>ES5</strong>, we probably also want to use <strong>arguments</strong> object.</p><pre>function sum() {<br>   var numbers = Array.prototype.slice.call(arguments),<br>       result = 0;<br>   numbers.forEach(function (number) {<br>       result += number;<br>   });<br>   return result;<br>}</pre><pre>console.log(sum(1));             // 1<br>console.log(sum(1, 2, 3, 4, 5)); // 15</pre><p>But it’s not obvious that the function is capable of handling any parameters. We have to scan a body of the function and find <strong>arguments</strong> object.</p><p><strong>ECMAScript 6</strong> introduces <strong>rest</strong> parameters to help us with this and other pitfalls.</p><blockquote>arguments - contains all parameters including named parameters</blockquote><p>Rest parameters are indicated by three dots <strong>…</strong> preceding a parameter. Named parameter becomes an <strong>array</strong> which contain the rest of the parameters.</p><p><strong>sum</strong> function can be rewritten using an ES6 syntax:</p><pre>function sum(…numbers) {<br>  var result = 0;<br>  numbers.forEach(function (number) {<br>    result += number;<br>  });<br>  return result;<br>}</pre><pre>console.log(sum(1)); // 1<br>console.log(sum(1, 2, 3, 4, 5)); // 15</pre><blockquote>Restriction: no other named arguments can follow in the function declaration.</blockquote><pre>function sum(…numbers, last) { // causes a syntax error<br>  var result = 0;<br>  numbers.forEach(function (number) {<br>    result += number;<br>  });<br>  return result;<br>}</pre><h4>spread</h4><p>The <strong>spread</strong> is closely related to rest parameters, because of <strong>…</strong> (three dots) notation. It allows to split an array to single arguments which are passed to the function as separate arguments.</p><p>Let’s define our <strong>sum</strong> function and pass <strong>spread</strong> to it:</p><pre>function sum(a, b, c) {<br>  return a + b + c;<br>}</pre><pre>var args = [1, 2, 3];<br>console.log(sum(…args)); // 6</pre><p>ES5 equivalent is:</p><pre>function sum(a, b, c) {<br>  return a + b + c;<br>}</pre><pre>var args = [1, 2, 3];<br>console.log(sum.apply(undefined, args)); // 6</pre><p>So instead using an <strong>apply</strong> function, we can just type <strong>…args</strong> and pass all array argument separately.</p><p>We can also mix standard arguments with spread operator:</p><pre>function sum(a, b, c) {<br>  return a + b + c;<br>}</pre><pre>var args = [1, 2];<br>console.log(sum(…args, 3)); // 6</pre><p>The result is the same. First two arguments are from args array, and the last passed argument is 3.</p><p>Next</p><p><a href="https://medium.com/p/13ca399f993a"></a></p><blockquote><em>Like it? </em><strong><em>Recommend it!</em></strong></blockquote><p><a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a></p><blockquote>Whole series is also available as an <strong>ebook</strong>. I published it on <a href="http://leanpub.com">leanpub.com</a></blockquote><p><a href="https://leanpub.com/ecmascript2015es6guide">ECMAScript 2015 guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbGHEO5gdr_MVNiYQLvK9A.jpeg" /></figure><p>Future is bright!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3ab0d2e0a5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ecmascript-2015/default-rest-spread-f3ab0d2e0a5e">ES6 — default + rest + spread</a> was originally published in <a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 — arrow functions]]></title>
            <link>https://medium.com/ecmascript-2015/arrow-functions-bb08eeb11667?source=rss----c8958ce340e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/bb08eeb11667</guid>
            <category><![CDATA[arrow]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[arrow-functions]]></category>
            <dc:creator><![CDATA[Maciej Rzepiński]]></dc:creator>
            <pubDate>Thu, 04 Jun 2015 21:02:14 GMT</pubDate>
            <atom:updated>2015-06-19T05:47:48.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*RQFLsbQumE-iNrXzs_Oz8g.jpeg" /></figure><h2>ES6 — arrow functions</h2><h3>Let’s talk about ECMAScript 2015</h3><p>Previous</p><p><a href="https://medium.com/p/35bca3b4a3c6"></a></p><p>Today I’m going to describe a new syntactic sugar which ES6 brings us soon. It’s called <strong>arrow functions</strong> (also known as a fat arrow function) which is a shorter syntax compared to function expressions and lexically binds <strong>this</strong> value.</p><blockquote>REMEMBER — Arrow functions are always anonymous.</blockquote><h4>Syntactic sugar</h4><p>How does it look? It’s a signature:</p><pre>([param] [, param]) =&gt; {<br> statements<br>}</pre><pre>           param =&gt; expression<br>(param1, param2) =&gt; { block }</pre><p>.. and it could be translated to:</p><pre>    () =&gt; { … }       // no argument<br>     x =&gt; { … }       // one argument<br>(x, y) =&gt; { … }       // several arguments</pre><pre>x =&gt; { return x * x } // block<br>x =&gt; x * x            // expression, same as above</pre><p>Lambda expressions in JavaScript! Cool!</p><p>So instead of writing:</p><pre>[3, 4, 5].map(function (n) {<br> return n * n;<br>});</pre><p>.. you can write something like this:</p><pre>[3, 4, 5].map(n =&gt; n * n);</pre><p>Awesome. Isn’t it? There is more!</p><h4>Fixed “this” = lexical “<strong>this”</strong></h4><blockquote>The value of this inside of the function is determined by where the arrow function is defined not where it is used.</blockquote><p>No more <strong>bind</strong>, <strong>call</strong> and <strong>apply</strong>! No more:</p><pre>var self = this;</pre><p>It solves a major pain point (from my point of view) and has the added bonus of improving performance through JavaScript engine optimizations.</p><pre>// ES5</pre><pre>function FancyObject() {<br> var self = this;<br> <br> self.name = &#39;FancyObject&#39;;</pre><pre> setTimeout(function () {<br>  self.name = &#39;Hello World!&#39;;<br> }, 1000);<br>}</pre><pre>// ES6</pre><pre>function FancyObject() {<br> this.name = &#39;FancyObject&#39;;</pre><pre> setTimeout(() =&gt; {<br>  this.name = &#39;Hello World!&#39;; // properly refers to FancyObject<br> }, 1000);<br>}</pre><h4>The same function</h4><ul><li><strong>typeof </strong>returns <strong>function</strong></li><li><strong>instanceof</strong> returns <strong>Function</strong></li></ul><h4>Limitations</h4><ul><li>It’s cannot be used as a constructor and will throw an error when used with <strong>new</strong>.</li><li>Fixed <strong>this</strong> means that you cannot change the <strong>value of this</strong> inside of the function. It remains the same value throughout the entire lifecycle of the function.</li><li>Regular functions can be <strong>named</strong>.</li><li>Functions declarations are <strong>hoisted (</strong>can be used before they are declared<strong>)</strong>.</li></ul><p>Next</p><p><a href="https://medium.com/p/f3ab0d2e0a5e"></a></p><blockquote><em>Like it? </em><strong><em>Recommend it!</em></strong></blockquote><p><a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a></p><blockquote>Whole series is also available as an <strong>ebook</strong>. I published it on <a href="http://leanpub.com">leanpub.com</a></blockquote><p><a href="https://leanpub.com/ecmascript2015es6guide">ECMAScript 2015 guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbGHEO5gdr_MVNiYQLvK9A.jpeg" /></figure><p>Future is bright!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb08eeb11667" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ecmascript-2015/arrow-functions-bb08eeb11667">ES6 — arrow functions</a> was originally published in <a href="https://medium.com/ecmascript-2015">ECMAScript 2015</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>