Playing around with react has recently led to a lot of contact with ES6 aka EcmaScript6 aka ES 2015. Here is a quick introduction to my six favorite features. The easiest way to play around with ES6 is with babel. To actually run the code try Firefox developer edition’s console.
I’ll be briefly covering block scoping, arrow functions, spread operators, object property shorthand, modules, and object destructuring
1. Block Scoping with let and const
var’s are scoped to their containing function.
const are scoped to their containing block. Block scoping cleans up some global pollution and makes things such as using multiple loops a breeze.
const is also immutable which is great if there is a variable you want to make sure doesn’t change.
2. Arrow Functions
=>. Anything in front of the arrow is an argument. If you are returning a single statement no
return is needed, it is returned implicitly. If it is not a simple statement you can still use
return like normal. Arrow functions are great for simplifying callbacks or really any anonymous function.
The only real difference between arrow functions and old fashioned anonymous functions is how
this, arrow functions don’t. They simply refer to their containing scope’s
3. Spread Operator
...spread The spread operator allows you to expand an array in place. This is really useful for combining arrays as well as accepting an unknown number of function arguments.
4. Object Property Shorthand
This nice little feature allows you to create objects with variables where the variable name is the key and the value is the variable value. Sounds so much more complicated than it really is.
Separating code into separate files is something most people do already, but it requires browserify, webpack, requirejs, or some other non-standard package that all come with their limitations and hassles. Now you can use modules natively where and when you want. You can export one thing or multiple named things from a module. Check out this post for a more thorough primer.
6. Object destructuring
With ES6 you can quickly pull out values from an object and set them to a variable with minimal syntax. The most common use case is when importing multiple things from a module.
Thanks for reading, I hope some of it was helpful. There are a ton more cool features in ES6 and even from future releases, but I found these were the easiest to start incoporating into code right now. Check out http://es6-features.org/ to see all of the ES6 features along with great examples.