5 ES2015 Features You Should Use Today
1. Block scope with “let” and “const”
Not anymore. When you declare variables with let or const they only exist in the block that you declared them. Ultimately, there is no reason to ever use var anymore, let and const should replace var completely.
2. Arrow functions
Arrow functions at first may appear just to be a new function declaration syntax, but they actually behave differently from traditional functions. In normal functions when you declare a function the value of “this” can be a little bit tricky because each function will create its own context. Arrow functions don’t create their own context, so when you reference “this”, you will ALWAYS be referencing the parent function. Check out this example, which shows “this” clearly belonging the parent function.
Promises have been around for a while but only as features of libraries. Whether you used jQuery, Angular $q, bluebird, or something else, everyone had their own implementations of promises. Now promises are baked into the language and can be used without external dependencies. So whether you like to use Promises or Callbacks for your async control flow, now you don’t need to weigh bringing in another dependency to make the decision.
4. Template Strings
Template strings (also known as template literals) allow you to perform string interpolation and define multiline strings as well as “tagging” (a way to modify the output of a template string with a function). To create a template string all you have to do is use backticks (
5. New Object Syntax
I’m going to cheat on #5 here and throw in a bunch of new syntax related to manipulating objects because it is all so cool. This includes Destructuring, Object property shorthands, the spread operator, and the new class declaration syntax. Destructuring, in particular, can be very nice and you will quickly find yourself thinking to apply it in all sorts of convenient ways. Check out the example below:
Next, I want to show a quick example of object property shorthand and use of the spread operator:
There are too many new features in ES2015 to detail in one short blog post, but here are some free egghead.io videos that can take this introduction a bit further.