{"id":5164,"date":"2019-01-31T17:52:34","date_gmt":"2019-01-31T16:52:34","guid":{"rendered":"https:\/\/monodes.com\/predaelli\/?p=5164"},"modified":"2019-01-31T09:29:38","modified_gmt":"2019-01-31T08:29:38","slug":"these-are-the-features-in-es6-that-you-should-know","status":"publish","type":"post","link":"https:\/\/monodes.com\/predaelli\/2019\/01\/31\/these-are-the-features-in-es6-that-you-should-know\/","title":{"rendered":"These are the features in ES6 that you should know"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\"><a href=\"https:\/\/medium.freecodecamp.org\/these-are-the-features-in-es6-that-you-should-know-1411194c71cb?mkt_tok=eyJpIjoiTkdOak1UQTBPR1kwWXpJNSIsInQiOiJcLzRpU2xOTGYxTkNhdUhjY0ltYXlcL2Z0cVwvSmhuVDhzTFpqV0FNUFA5YlVOZnljeWRoTjBiakhTNjZ6VHo4eEVkK1JwT2FNa2NBWVU4T0x1UG00ZGp2aHI2VlAxd2VvS1dtOUp5M3NFdnhlVWZLWjJhaTdrRXdhMXdIa1J4ZmtMbyJ9\">These are the features in ES6 that you should know<\/a><\/h2>\n\n\n\n<!--nextpage-->\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>These are the features in ES6 that you should know<\/p><p><a href=\"https:\/\/medium.freecodecamp.org\/@cristisalcescu\">by Cristi Salcescu<\/a><br \/><br \/>ES6  brings more features to the JavaScript language. Some new syntax allows  you to write code in a more expressive way, some features complete the  functional programming toolbox, and some features are questionable.<br \/>let and\u00a0const<br \/>There are two ways for declaring a variable (<code class=\"\" data-line=\"\">let<\/code> and <code class=\"\" data-line=\"\">const<\/code>) plus one that has become obsolete (<code class=\"\" data-line=\"\">var<\/code>).<br \/>let<br \/><code class=\"\" data-line=\"\">let<\/code>  declares and optionally initializes a variable in the current scope.  The current scope can be either a module, a function or a block. The  value of a variable that is not initialized is <code class=\"\" data-line=\"\">undefined<\/code>\u00a0.<br \/>Scope defines the lifetime and visibility of a variable. Variables are not visible outside the scope in which they are declared.<br \/>Consider the next code that emphasizes <code class=\"\" data-line=\"\">let<\/code> block scope:<br \/>let x = 1;<br \/>{ <br \/>  let x = 2;<br \/>}<br \/>console.log(x); \/\/1<br \/>In contrast, the <code class=\"\" data-line=\"\">var<\/code> declaration had no block scope:<br \/>var x = 1;<br \/>{ <br \/>  var x = 2;<br \/>}<br \/>console.log(x); \/\/2<br \/>The <code class=\"\" data-line=\"\">for<\/code> loop statement, with the <code class=\"\" data-line=\"\">let<\/code>  declaration, creates a new variable local to the block scope, for each  iteration. The next loop creates five closures over five different <code class=\"\" data-line=\"\">i<\/code> variables.<br \/>(function run(){<br \/>  for(let i=0; i&lt;5; i++){<br \/>    setTimeout(function log(){<br \/>      console.log(i); \/\/0 1 2 3 4<br \/>    }, 100);<br \/>  }<br \/>})();<br \/>Writing the same code with <code class=\"\" data-line=\"\">var<\/code> will create five closures, over the same variable, so all closures will display the last value of <code class=\"\" data-line=\"\">i<\/code>.<br \/>The <code class=\"\" data-line=\"\">log()<\/code> function is a closure. For more on closures, take a look at <a rel=\"noreferrer noopener\" href=\"https:\/\/medium.freecodecamp.org\/discover-the-power-of-closures-in-javascript-5c472a7765d7\" target=\"_blank\">Discover the power of closures in JavaScript<\/a>.<br \/>const<br \/><code class=\"\" data-line=\"\">const<\/code> declares a variable that cannot be reassigned. It becomes a constant only when the assigned value is immutable.<br \/>An immutable value is a value that, once created, cannot be changed. Primitive values are immutable, objects are mutable.<br \/><code class=\"\" data-line=\"\">const<\/code> freezes the variable, <code class=\"\" data-line=\"\">Object.freeze()<\/code> freezes the object.<br \/>The initialization of the <code class=\"\" data-line=\"\">const<\/code> variable is mandatory.<br \/>Modules<br \/>Before modules, a variable declared outside any function was a global variable.<br \/>With  modules, a variable declared outside any function is hidden and not  available to other modules unless it is explicitly exported.<br \/>Exporting makes a function or object available to other modules. In the next example, I export functions from different modules:<br \/>\/\/module &#8220;.\/TodoStore.js&#8221;<br \/>export default function TodoStore(){}<br \/>\/\/module &#8220;.\/UserStore.js&#8221;<br \/>export default function UserStore(){}<br \/>Importing makes a function or object, from other modules, available to the current module.<br \/>import TodoStore from &#8220;.\/TodoStore&#8221;;<br \/>import UserStore from &#8220;.\/UserStore&#8221;;<br \/>const todoStore = TodoStore();<br \/>const userStore = UserStore();<br \/>Spread\/Rest<br \/>The\u00a0<code class=\"\" data-line=\"\">\u2026<\/code> operator can be the spread operator or the rest parameter, depending on where it is used. Consider the next example:<br \/>const numbers = [1, 2, 3];<br \/>const arr = [&#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217;, <strong>&#8230;numbers<\/strong>];<br \/>console.log(arr);<br \/>[&#8220;a&#8221;, &#8220;b&#8221;, &#8220;c&#8221;, 1, 2, 3]<br \/>This is the spread operator. Now look at the next example:<br \/>function process(x,y, <strong>&#8230;arr<\/strong>){<br \/>  console.log(arr)<br \/>}<br \/>process(1,2,3,4,5);<br \/>\/\/[3, 4, 5]<br \/>function processArray(<strong>&#8230;arr<\/strong>){<br \/>  console.log(arr)<br \/>}<br \/>processArray(1,2,3,4,5);<br \/>\/\/[1, 2, 3, 4, 5]<br \/>This is the rest parameter.<br \/>arguments<br \/>With the rest parameter we can replace the <code class=\"\" data-line=\"\">arguments<\/code> pseudo-parameter. The rest parameter is an array, <code class=\"\" data-line=\"\">arguments<\/code> is not.<br \/>function addNumber(total, value){<br \/>  return total + value;<br \/>}<br \/>function sum(<strong>&#8230;args<\/strong>){<br \/>  return <strong>args.reduce(addNumber, 0)<\/strong>;<br \/>}<br \/>sum(1,2,3); \/\/6<br \/>Cloning<br \/>The spread operator makes the cloning of objects and arrays simpler and more expressive.<br \/>const book = { title: &#8220;JavaScript: The Good Parts&#8221; };<br \/>\/\/clone with Object.assign()<br \/>const clone = Object.assign({}, book);<br \/>\/\/clone with spread operator<br \/><strong>const clone = { &#8230;book };<\/strong><br \/>const arr = [1, 2 ,3];<br \/>\/\/clone with slice<br \/>const cloneArr = arr.slice();<br \/>\/\/clone with spread operator<br \/><strong>const cloneArr = [ &#8230;arr ];<\/strong><br \/>Concatenation<br \/>In the next example, the spread operator is used to concatenate arrays:<br \/>const part1 = [1, 2, 3];<br \/>const part2 = [4, 5, 6];<br \/>const arr = part1.concat(part2);<br \/><strong>const arr = [&#8230;part1, &#8230;part2];<\/strong><br \/>Multiple inheritance<br \/>The spread operator, like <code class=\"\" data-line=\"\">Object.assign()<\/code>, can be used to copy properties from one or more objects to an empty object and do multiple inheritance.<br \/>const authorGateway = { <br \/>  getAuthors : function() {},<br \/>  editAuthor: function() {}<br \/>};<br \/>const bookGateway = { <br \/>  getBooks : function() {},<br \/>  editBook: function() {}<br \/>};<br \/>\/\/copy with Object.assign()<br \/>const gateway = Object.assign({},<br \/>      authorGateway, <br \/>      bookGateway);<br \/>      <br \/>\/\/copy with spread operator<br \/>const gateway = {<br \/>   &#8230;authorGateway,<br \/>   &#8230;bookGateway<br \/>};<br \/>Property short-hands<br \/>Consider the next code:<br \/>function BookGateway(){<br \/>  function getBooks() {}<br \/>  function editBook() {}<br \/>  <br \/>  return {<br \/>    getBooks: getBooks,<br \/>    editBook: editBook<br \/>  }<br \/>}<br \/>With  property short-hands, when the property name and the name of the  variable used as the value are the same, we can just write the key once.<br \/>function BookGateway(){<br \/>  function getBooks() {}<br \/>  function editBook() {}<br \/>  <br \/>  return <strong>{<br \/>    getBooks,<br \/>    editBook<br \/>  }<\/strong><br \/>}<br \/>Here is another example:<br \/>const todoStore = TodoStore();<br \/>const userStore = UserStore();<br \/>    <br \/>const stores = <strong>{<br \/>  todoStore,<br \/>  userStore<br \/>};<\/strong><br \/>Destructuring assignment<br \/>Consider the next code:<br \/>function TodoStore(args){<br \/>  const helper = args.helper;<br \/>  const dataAccess = args.dataAccess;<br \/>  const userStore = args.userStore;<br \/>}<br \/>With destructuring assignment syntax, it can be written like this:<br \/>function TodoStore(args){<br \/><strong>   const { <br \/>      helper, <br \/>      dataAccess, <br \/>      userStore } = args;<\/strong><br \/>}<br \/>or even better, with the destructuring syntax in the parameter list:<br \/>function TodoStore(<strong>{ helper, dataAccess, userStore }<\/strong>){}<br \/>Below is the function call:<br \/>TodoStore({ <br \/>  helper: {}, <br \/>  dataAccess: {}, <br \/>  userStore: {} <br \/>});<br \/>Default parameters<br \/>Functions can have default parameters. Look at the next example:<br \/>function log(message, <strong>mode = &#8220;Info&#8221;<\/strong>){<br \/>  console.log(mode + &#8220;: &#8221; + message);<br \/>}<br \/>log(&#8220;An info&#8221;);<br \/>\/\/Info: An info<br \/>log(&#8220;An error&#8221;, &#8220;Error&#8221;);<br \/>\/\/Error: An error<br \/>Template string\u00a0literals<br \/>Template strings are defined with the <code class=\"\" data-line=\"\">`<\/code> charter. With template strings, the previous logging message can be written like this:<br \/>function log(message, mode= &#8220;Info&#8221;){<br \/>  console.log(<strong>`${mode}: ${message}`<\/strong>);<br \/>}<br \/>Template  strings can be defined on multiple lines. However, a better option is  to keep the long text messages as resources, in a database for example.<br \/>See below a function that generates an HTML that spans multiple lines:<br \/>function createTodoItemHtml(todo){<br \/>  return `&lt;li><br \/>    &lt;div>${todo.title}&lt;\/div><br \/>    &lt;div>${todo.userName}&lt;\/div><br \/>  &lt;\/li>`;<br \/>}<br \/>Proper tail-calls<br \/>A recursive function is tail recursive when the recursive call is the last thing the function does.<br \/>The  tail recursive functions perform better than non tail recursive  functions. The optimized tail recursive call does not create a new stack  frame for each function call, but rather uses a single stack frame.<br \/>ES6 brings the tail-call optimization in strict mode.<br \/><a rel=\"noreferrer noopener\" href=\"https:\/\/jsfiddle.net\/cristi_salcescu\/4t2j3uho\/\" target=\"_blank\">The following function<\/a> should benefit from the tail-call optimization.<br \/>function print(from, to) <br \/>{ <br \/>  const n = from;<br \/>  if (n > to)  return;<br \/>  <br \/>  console.log(n);<br \/><strong>  \/\/the last statement is the recursive call <br \/>  print(n + 1, to); <\/strong><br \/>}<br \/>print(1, 10);<br \/>Note: the tail-call optimization is not yet supported by major browsers.<br \/>Promises<br \/>A promise is a reference to an asynchronous call. It may resolve or fail somewhere in the future.<br \/>Promises are easier to combine. <a rel=\"noreferrer noopener\" href=\"https:\/\/jsfiddle.net\/cristi_salcescu\/eqyhq2e3\/\" target=\"_blank\">As you see in the next example<\/a>, it is easy to call a function when all promises are resolved, or when the first promise is resolved.<br \/>function getTodos() { return fetch(&#8220;<a rel=\"noreferrer noopener\" href=\"https:\/\/jsonplaceholder.typicode.com\/albums\" target=\"_blank\">\/<\/a><a rel=\"noreferrer noopener\" href=\"https:\/\/jsonplaceholder.typicode.com\/todos\" target=\"_blank\">todos<\/a>&#8220;); }<br \/>function getUsers() { return fetch(&#8220;<a rel=\"noreferrer noopener\" href=\"https:\/\/jsonplaceholder.typicode.com\/albums\" target=\"_blank\">\/<\/a><a rel=\"noreferrer noopener\" href=\"https:\/\/jsonplaceholder.typicode.com\/users\" target=\"_blank\">users<\/a>&#8220;); }<br \/>function getAlbums(){ return fetch(&#8220;<a rel=\"noreferrer noopener\" href=\"https:\/\/jsonplaceholder.typicode.com\/albums\" target=\"_blank\">\/albums<\/a>&#8220;); }<br \/>const getPromises = [<br \/>  getTodos(), <br \/>  getUsers(), <br \/>  getAlbums()<br \/>];<br \/>Promise.all(getPromises).then(doSomethingWhenAll);<br \/>Promise.race(getPromises).then(doSomethingWhenOne);<br \/>function doSomethingWhenAll(){}<br \/>function doSomethingWhenOne(){}<br \/>The <code class=\"\" data-line=\"\">fetch()<\/code> function, part of the Fetch API, returns a promise.<br \/><code class=\"\" data-line=\"\">Promise.all()<\/code> returns a promise that resolves when all input promises have resolved. <code class=\"\" data-line=\"\">Promise.race()<\/code> returns a promise that resolves or rejects when one of the input promises resolves or rejects.<br \/>A  promise can be in one of the three states: pending, resolved or  rejected. The promise will in pending until is either resolved or  rejected.<br \/>Promises support a chaining system that allows you to pass data through a set of functions. <a rel=\"noreferrer noopener\" href=\"https:\/\/jsfiddle.net\/cristi_salcescu\/kgxnay46\/\" target=\"_blank\">In the next example<\/a>, the result of <code class=\"\" data-line=\"\">getTodos()<\/code> is passes as input to <code class=\"\" data-line=\"\">toJson()<\/code>, then its result is passed as input to <code class=\"\" data-line=\"\">getTopPriority()<\/code>, and then its result is passed as input to <code class=\"\" data-line=\"\">renderTodos()<\/code> function. When an error is thrown or a promise is rejected the <code class=\"\" data-line=\"\">handleError<\/code> is called.<br \/>getTodos()<br \/>  .then(toJson)<br \/>  .then(getTopPriority)<br \/>  .then(renderTodos)<br \/>  .catch(handleError);<br \/>function toJson(response){}<br \/>function getTopPriority(todos){}<br \/>function renderTodos(todos){}<br \/>function handleError(error){}<br \/>In the previous example,\u00a0<code class=\"\" data-line=\"\">.then()<\/code> handles the success scenario and\u00a0<code class=\"\" data-line=\"\">.catch()<\/code>  handles the error scenario. If there is an error at any step, the chain  control jumps to the closest rejection handler down the chain.<br \/><code class=\"\" data-line=\"\">Promise.resolve()<\/code> returns a resolved promise. <code class=\"\" data-line=\"\">Promise.reject()<\/code> returns a rejected promise.<br \/>Class<br \/>Class  is sugar syntax for creating objects with a custom prototype. It has a  better syntax than the previous one, the function constructor. <a rel=\"noreferrer noopener\" href=\"https:\/\/jsfiddle.net\/cristi_salcescu\/aLg8t632\/\" target=\"_blank\">Check out the next exemple<\/a>:<br \/>class Service {<br \/>  doSomething(){ console.log(&#8220;doSomething&#8221;); }<br \/>}<br \/>let service = new Service();<br \/>console.log(service.__proto__ === Service.prototype);<br \/>All methods defined in the <code class=\"\" data-line=\"\">Service<\/code> class will be added to the<code class=\"\" data-line=\"\">Service.prototype<\/code> object. Instances of the <code class=\"\" data-line=\"\">Service<\/code> class will have the same prototype (<code class=\"\" data-line=\"\">Service.prototype<\/code>) object. All instances will delegate method calls to the <code class=\"\" data-line=\"\">Service.prototype<\/code> object. Methods are defined once on<code class=\"\" data-line=\"\">Service.prototype<\/code> and then inherited by all instances.<br \/>Inheritance<br \/>\u201cClasses can inherit from other classes\u201d. Below is an <a rel=\"noreferrer noopener\" href=\"https:\/\/jsfiddle.net\/cristi_salcescu\/1xo96yt8\/\" target=\"_blank\">example of inheritance<\/a> where the <code class=\"\" data-line=\"\">SpecialService<\/code> class \u201cinherits\u201d from the <code class=\"\" data-line=\"\">Service<\/code> class:<br \/>class Service {<br \/>  doSomething(){ console.log(&#8220;doSomething&#8221;); }<br \/>}<br \/><strong>class SpecialService extends Service<\/strong> {<br \/>  doSomethingElse(){ console.log(&#8220;doSomethingElse&#8221;); }  <br \/>}<br \/>let specialService = new SpecialService();<br \/>specialService.doSomething();<br \/>specialService.doSomethingElse();<br \/>All methods defined in the <code class=\"\" data-line=\"\">SpecialService<\/code> class will be added to the <code class=\"\" data-line=\"\">SpecialService.prototype<\/code> object. All instances will delegate method calls to the <code class=\"\" data-line=\"\">SpecialService.prototype<\/code> object. If the method is not found in <code class=\"\" data-line=\"\">SpecialService.prototype<\/code>, it will be searched in the <code class=\"\" data-line=\"\">Service.prototype<\/code> object. If it is still not found, it will be searched in <code class=\"\" data-line=\"\">Object.prototype<\/code>.<br \/>Class can become a bad\u00a0feature<br \/>Even if they seem encapsulated, all members of a class are public. You still need to manage problems with <code class=\"\" data-line=\"\">this<\/code> losing context. The public API is mutable.<br \/><code class=\"\" data-line=\"\">class<\/code> can become a bad feature if you neglect the functional side of JavaScript. <code class=\"\" data-line=\"\">class<\/code>  may give the impression of a class-based language when JavaScript is  both a functional programming language and a prototype-based language.<br \/>Encapsulated objects can be created with factory functions. Consider the next example:<br \/>function Service() {<br \/>  function doSomething(){ console.log(&#8220;doSomething&#8221;); }<br \/>  <br \/>  return Object.freeze({<br \/>     doSomething<br \/>  });<br \/>}<br \/>This time all members are private by default. The public API is immutable. There is no need to manage issues with <code class=\"\" data-line=\"\">this<\/code> losing context.<br \/><code class=\"\" data-line=\"\">class<\/code>  may be used as an exception if required by the components framework.  This was the case with React, but is not the case anymore with <a rel=\"noreferrer noopener\" href=\"https:\/\/reactjs.org\/docs\/hooks-overview.html\" target=\"_blank\">React Hooks<\/a>.<br \/>For more on why to favor factory functions, take a look at <a rel=\"noreferrer noopener\" href=\"https:\/\/medium.freecodecamp.org\/class-vs-factory-function-exploring-the-way-forward-73258b6a8d15\" target=\"_blank\">Class vs Factory function: exploring the way forward<\/a>.<br \/>Arrow functions<br \/>Arrow functions can create anonymous functions on the fly. They can be used to create small callbacks, with a shorter syntax.<br \/>Let\u2019s take a collection of to-dos. A to-do has an <code class=\"\" data-line=\"\">id<\/code>\u00a0, a <code class=\"\" data-line=\"\">title<\/code>\u00a0, and a <code class=\"\" data-line=\"\">completed<\/code> boolean property. Now, consider the next code that selects only the <code class=\"\" data-line=\"\">title<\/code> from the collection:<br \/>const titles = todos.map(todo => todo.title);<br \/>or the next example selecting only the <code class=\"\" data-line=\"\">todos<\/code> that are not completed:<br \/>const filteredTodos = todos.filter(todo => !todo.completed);<br \/>this<br \/>Arrow functions don\u2019t have their own <code class=\"\" data-line=\"\">this<\/code> and <code class=\"\" data-line=\"\">arguments<\/code>. As a result, you may see the arrow function used to fix problems with <code class=\"\" data-line=\"\">this<\/code> losing context. I think that the best way to avoid this problem is to not use <code class=\"\" data-line=\"\">this<\/code> at all.<br \/>Arrow functions can become a bad\u00a0feature<br \/>Arrow  functions can become a bad feature when used to the detriment of named  functions. This will create readability and maintainability problems.  Look at the next code written only with anonymous arrow functions:<br \/>const newTodos = todos.filter(todo => <br \/>       !todo.completed &amp;&amp; todo.type === &#8220;RE&#8221;)<br \/>    .map(todo => ({<br \/>       title : todo.title,<br \/>       userName : users[todo.userId].name<br \/>    }))<br \/>    .sort((todo1, todo2) =>  <br \/>      todo1.userName.localeCompare(todo2.userName));<br \/><a rel=\"noreferrer noopener\" href=\"https:\/\/jsfiddle.net\/cristi_salcescu\/pm7n2ab5\/\" target=\"_blank\">Now, check out the same logic<\/a> refactored to pure functions with intention revealing names and decide which of them is easier to understand:<br \/>const newTodos = <strong>todos.filter(isTopPriority)<br \/>  .map(partial(toTodoView, users))<br \/>  .sort(ascByUserName);<\/strong><br \/><strong>function isTopPriority(todo){<\/strong><br \/>  return !todo.completed &amp;&amp; todo.type === &#8220;RE&#8221;;<br \/><strong>}<\/strong><br \/>  <br \/><strong>function toTodoView(users, todo){<\/strong><br \/>  return {<br \/>    title : todo.title,<br \/>    userName : users[todo.userId].name<br \/>  }<br \/><strong>}<\/strong><br \/><strong>function ascByUserName(todo1, todo2){<\/strong><br \/>  return todo1.userName.localeCompare(todo2.userName);<br \/><strong>}<\/strong><br \/>Even more, anonymous arrow functions will appear as <code class=\"\" data-line=\"\">(anonymous)<\/code> in the Call Stack.<br \/>For more on why to favor named functions, take a look at <a rel=\"noreferrer noopener\" href=\"https:\/\/medium.freecodecamp.org\/how-to-make-your-code-better-with-intention-revealing-function-names-6c8b5271693e\" target=\"_blank\">How to make your code better with intention-revealing function names<\/a>.<br \/>Less code doesn\u2019t necessary mean more readable. <a rel=\"noreferrer noopener\" href=\"https:\/\/jsfiddle.net\/cristi_salcescu\/wc8be2gn\/\" target=\"_blank\">Look at the next example<\/a> and see which version is easier for you to understand:<br \/>\/\/with arrow function<br \/>const prop = key => obj => obj[key];<br \/>\/\/with function keyword<br \/>function prop(key){<br \/>   return function(obj){<br \/>      return obj[key];<br \/>   }<br \/>}<br \/>Pay attention when returning an object. In the next example, the <code class=\"\" data-line=\"\">getSampleTodo()<\/code> returns <code class=\"\" data-line=\"\">undefined<\/code>.<br \/>const getSampleTodo = () => { title : &#8220;A sample todo&#8221; };<br \/>getSampleTodo();<br \/>\/\/undefined<br \/>Generators<br \/>I think the ES6 generator is an unnecessary feature that makes code more complicated.<br \/>The ES6 generator creates an object that has the <code class=\"\" data-line=\"\">next()<\/code> method. The <code class=\"\" data-line=\"\">next()<\/code> method creates an object that has the <code class=\"\" data-line=\"\">value<\/code> property. ES6 generators promote the use of loops. <a rel=\"noreferrer noopener\" href=\"https:\/\/jsfiddle.net\/cristi_salcescu\/edq7vfwm\/\" target=\"_blank\">Take a look at code below<\/a>:<br \/>function* sequence(){<br \/>  let count = 0;<br \/>  while(true) {<br \/>    count += 1;<br \/>    yield count;<br \/>  }<br \/>}<br \/>const generator = sequence();<br \/>generator.next().value;\/\/1<br \/>generator.next().value;\/\/2<br \/>generator.next().value;\/\/3<br \/>The same generator can be simply implemented with a closure.<br \/>function sequence(){<br \/>  let count = 0;<br \/>  return function(){<br \/>    count += 1;<br \/>    return count;<br \/>  }<br \/>}<br \/>const generator = sequence();<br \/>generator();\/\/1<br \/>generator();\/\/2<br \/>generator();\/\/3<br \/>For more examples with functional generators take a look at <a rel=\"noreferrer noopener\" href=\"https:\/\/medium.freecodecamp.org\/lets-experiment-with-functional-generators-and-the-pipeline-operator-in-javascript-520364f97448\" target=\"_blank\">Let\u2019s experiment with functional generators and the pipeline operator in JavaScript<\/a><br \/>Conclusion<br \/><code class=\"\" data-line=\"\">let<\/code> and <code class=\"\" data-line=\"\">const<\/code> declare and initialize variables.<br \/>Modules encapsulate functionality and expose only a small part.<br \/>The spread operator, rest parameter, and property shorthand make things easier to express.<br \/>Promises and tail recursion complete the functional programming toolbox.<br \/>For more on JavaScript take a look\u00a0at:<br \/><a rel=\"noreferrer noopener\" href=\"https:\/\/medium.freecodecamp.org\/discover-functional-programming-in-javascript-with-this-thorough-introduction-a2ad9af2d645\" target=\"_blank\">Discover Functional Programming in JavaScript with this thorough introduction<\/a><br \/><a rel=\"noreferrer noopener\" href=\"https:\/\/medium.freecodecamp.org\/learn-these-javascript-fundamentals-and-become-a-better-developer-2a031a0dc9cf\" target=\"_blank\">Learn these JavaScript fundamentals and become a better developer<\/a><br \/><a rel=\"noreferrer noopener\" href=\"https:\/\/medium.freecodecamp.org\/lets-explore-objects-in-javascript-4a4ad76af798\" target=\"_blank\">Let\u2019s explore objects in JavaScript<\/a><br \/><a rel=\"noreferrer noopener\" href=\"https:\/\/medium.freecodecamp.org\/how-point-free-composition-will-make-you-a-better-functional-programmer-33dcb910303a\" target=\"_blank\">How point-free composition will make you a better functional programmer<\/a><br \/><a rel=\"noreferrer noopener\" href=\"https:\/\/medium.freecodecamp.org\/how-to-make-your-code-better-with-intention-revealing-function-names-6c8b5271693e\" target=\"_blank\">How to make your code better with intention-revealing function names<\/a><br \/><a rel=\"noreferrer noopener\" href=\"https:\/\/medium.freecodecamp.org\/make-your-code-easier-to-read-with-functional-programming-94fb8cc69f9d\" target=\"_blank\">Make your code easier to read with Functional Programming<\/a><\/p><\/blockquote>\n","protected":false},"excerpt":{"rendered":"<p class=\"excerpt\">These are the features in ES6 that you should know<\/p>\n<p class=\"more-link-p\"><a class=\"more-link\" href=\"https:\/\/monodes.com\/predaelli\/2019\/01\/31\/these-are-the-features-in-es6-that-you-should-know\/\">Read more &rarr;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"activitypub_content_warning":"","activitypub_content_visibility":"","activitypub_max_image_attachments":4,"activitypub_interaction_policy_quote":"anyone","activitypub_status":"","footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[72,50],"tags":[],"class_list":["post-5164","post","type-post","status-publish","format-standard","hentry","category-documentations","category-javascript"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p6daft-1li","jetpack-related-posts":[{"id":5713,"url":"https:\/\/monodes.com\/predaelli\/2019\/06\/12\/5713\/","url_meta":{"origin":5164,"position":0},"title":"Different ways to achieve encapsulation\u2026","author":"Paolo Redaelli","date":"2019-06-12","format":"link","excerpt":"Different ways to achieve encapsulation in JavaScript(ES6) Iskander Samatov","rel":"","context":"In &quot;Javascript&quot;","block_context":{"text":"Javascript","link":"https:\/\/monodes.com\/predaelli\/category\/javascript\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":4373,"url":"https:\/\/monodes.com\/predaelli\/2018\/06\/13\/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt\/","url_meta":{"origin":5164,"position":1},"title":"When (and why) you should use ES6 arrow functions \u2014 and when you shouldn\u2019t","author":"Paolo Redaelli","date":"2018-06-13","format":false,"excerpt":"Nice reminder. Arrow functions (also called \u201cfat arrow functions\u201d) are undoubtedly one of the more popular features of ES6. They introduced a new way of\u2026 Sorgente: When (and why) you should use ES6 arrow functions \u2014 and when you shouldn\u2019t Arrow functions (also called \u201cfat arrow functions\u201d) are undoubtedly one\u2026","rel":"","context":"In &quot;Documentations&quot;","block_context":{"text":"Documentations","link":"https:\/\/monodes.com\/predaelli\/category\/documentations\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2140,"url":"https:\/\/monodes.com\/predaelli\/2017\/02\/03\/2140\/","url_meta":{"origin":5164,"position":2},"title":"http:\/\/jamesknelson.com\/using-es6-in-the-browser-with-babel-6-and-webpack\/","author":"Paolo Redaelli","date":"2017-02-03","format":false,"excerpt":"http:\/\/jamesknelson.com\/using-es6-in-the-browser-with-babel-6-and-webpack\/","rel":"","context":"In &quot;Documentations&quot;","block_context":{"text":"Documentations","link":"https:\/\/monodes.com\/predaelli\/category\/documentations\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":8190,"url":"https:\/\/monodes.com\/predaelli\/2021\/02\/21\/typeorm\/","url_meta":{"origin":5164,"position":3},"title":"Typeorm","author":"Paolo Redaelli","date":"2021-02-21","format":"link","excerpt":"typeorm.io is Object\u2013relational mapping for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.","rel":"","context":"In &quot;Javascript&quot;","block_context":{"text":"Javascript","link":"https:\/\/monodes.com\/predaelli\/category\/javascript\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":3264,"url":"https:\/\/monodes.com\/predaelli\/2017\/08\/10\/this-in-javascript-zell-liew\/","url_meta":{"origin":5164,"position":4},"title":"This in JavaScript | Zell Liew","author":"Paolo Redaelli","date":"2017-08-10","format":"link","excerpt":"https:\/\/zellwk.com\/blog\/this\/ This is really nice to read Hire me This in JavaScript 21st Jun 2017 Are you confused by the this keyword in JavaScript? It confuses everyone in the beginning, so don\u2019t worry about it. You\u2019re not alone. But that doesn\u2019t mean you can go on without understanding this forever.\u2026","rel":"","context":"In &quot;Javascript&quot;","block_context":{"text":"Javascript","link":"https:\/\/monodes.com\/predaelli\/category\/javascript\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1737,"url":"https:\/\/monodes.com\/predaelli\/2016\/08\/18\/math-js\/","url_meta":{"origin":5164,"position":5},"title":"math.js","author":"Paolo Redaelli","date":"2016-08-18","format":"link","excerpt":"Math.js is an extensive math library for JavaScript and Node.js. It features big numbers, complex numbers, matrices, units, and a flexible expression parser. Sorgente: math.js","rel":"","context":"In &quot;Javascript&quot;","block_context":{"text":"Javascript","link":"https:\/\/monodes.com\/predaelli\/category\/javascript\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts\/5164","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/comments?post=5164"}],"version-history":[{"count":0,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/posts\/5164\/revisions"}],"wp:attachment":[{"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/media?parent=5164"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/categories?post=5164"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/monodes.com\/predaelli\/wp-json\/wp\/v2\/tags?post=5164"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}