The 6 Coolest things about ES6

giphy-1

ECMAScript 6 is the most recent update to JavaScript. Most of its features can be called “sugar”, things that don’t change the underlying processes or structure of Javascript, but make your code cleaner, easier to read, and more similar to code written in other common programming languages. Many browsers haven’t adapted to ES6 yet, but here are a few features that are already changing the way I write code, complete with examples.

  1. Arrow Functions
    • Some say that arrow functions are funny looking, but I think they’re beautiful. They especially help clean up your code if you are writing simple callback functions. For example, this is the code to sort an array of numbers from least to greatest without arrow functions:
      var arr = [15, 8, 4, 16, 42, 23]; 
      arr.sort(function(a, b){
          return a>b; 
      }); 
      

      And here is the code to do the same thing with arrow functions:

      let arr = [15, 8, 4, 16, 42, 23];
      arr.sort((a,b) => a > b); 
      

      Nice right? I don’t even know what I’m going to do with all my extra time now that I don’t have to write “function” or “return.” They also help with certain situations where you want more control over the “this” keyword, but I won’t get into that here.

  2. Default parameters
    • Another cool time saver. JavaScript allows you to call basically any function with basically any amount of parameters that you feel like at the time, which is cool,  but it can be problematic if you are writing a function and you expect all your parameters to be defined. It is often necessary to assign default parameters. For example, this function will say “hello” to you if you pass it your name, otherwise it will say “Hello, Earthling!” :
      function sayHello(name){
        var person = name || "Earthling";
        console.log("Hello," + person + "!");
      }
      

      There are a few other ways to assign defaults pre ES6, but as far as I know, they all require at least one extra line of code. Enter ES6 Default Parameters:

      function sayHello(name = "Earthling"){
        console.log("Hello," + name + "!");
      }
      

      Boom, there goes that line. Now, that might not seem like a lot in this context, but for functions with multiple parameters, you’re saving yourself a lot of code.

  3. The for…of loop
    • ES6 does some really nice things for arrays, and the for… of loop is one of them. This loop has the potential to be pretty life changing, since basically everything that happens on a computer requires some array or array-esque thing to be looped through. Here are a few ways to loop through arrays the OLD way. You could use an old-school for loop:
      var arr = [4, 8, 15, 16, 23, 42]; // assume this line in each ex. 
      for (var i = 0; i< arr.length; i++){
         console.log(arr[i]); 
      }
      

      This is still sometimes the best option because it gives you total control over the array and the manner in which you’re iterating over it, but it’s not very semantic – the words on the page don’t tell you a lot about what you are trying to do. Enter for each, which is more semantic but annoyingly requires a callback function:

      arr.forEach(function(num){
         console.log(num); 
      }); 
      

      This is more semantic, since it tells us that we are performing an operation “for each” “num” in the array. And, admittedly, you can clean up the callback with an arrow function, but this is still just too much thinking sometimes. Pre-ES6 you still have one more option, if you REALLY want to, of using the object iterator for…in:

      for (var idx in arr){
         console.log(arr[idx]); 
      }
      

      This is a pretty good option, but we’re back to referring to array elements by their indexes instead of by name. Enter ES6’s for…of loop!

      for (let num of arr){
         console.log(num); 
      }
      

      Ahhh. perfect. So sleek, so clean, so semantic, no callbacks. You can even make other objects iterable in this way, although I’m not sold that that will ever be a good idea. Time will tell.

  4. Assignment with Array Destructuring 
    • Let’s say you’ve got an array of stuff and you want to give names to that stuff. You could do that the old way:
      var prices = [2, 45, 6, 19, 32]; 
      var cookie = prices[0]; 
      var lobsterDinner = prices[1]; 
      var rest = prices.slice(2); 
      

      Now cookie = 2, lobsterDinner = 45, and rest = [6, 19, 32]. It did the job, but that was pretty hard to look at. Enter ES6:

      let prices = [2, 45, 6, 19, 32];
      let [cookie, lobsterDinner, ...rest] = prices;   
      

      Nuff said.

  5. The Spread Operator 
    • This thing isn’t all that handy, except for when it’s VERY handy. Putting a … before an array essentially chops that array up into its individual elements, particularly in the argument of a function. Here’s a cool example. Say you want to find the maximum element in an array of numbers. You could do it the yuck way:
      var max = Math.max.apply(null, arr); 
      

      Or the ES6 way:

      var max = Math.max(...arr); 
      

      Much cuter. You can also do it in reverse, which comes in handy when you’re trying to convert the arguments object into a proper array. The old way:

      function example(){
         var args = Array.prototype.slice.call(arguments); 
      }
      

      I’m sorry I made you look at that. Let’s do it with ES6:

      function example(){
         var args = [...arguments]; 
      }
      

      Nice. Edit: You can even do away with the arguments object complely by simply declaring your function thusly:  function(...args){}

  6.  Sleek object assignment 
    • I don’t actually know the technical name for this thing, or if it even has a technical name, but it’s awesome. Let’s say you want to create an object based on parameters in a function or some other variables that you have laying around. And let’s say you want the keys in the object to have the same names as the variables. This could get very repetitive:
      function eatYourVeggies(carrots, broccolini, beets){
         var veggieObj = {
            carrots: carrots, 
            broccolini: broccolini, 
            beets: beets
         }; 
      }

      but not with ES6!

      function eatYourVeggies(carrots, broccolini, beets){
         let veggieObj = {carrots, broccolini, beets}; 
      }

      Never again will you experience the agony of writing the same word twice in a row.

There’s a lot else to love about ES6. Const and let, for example, or native promises. But these 6 examples stand out to me as the most simple, elegant, and readable. I can’t wait to start using them!

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s