JavaScript ES6 The Best Parts

JavaScript ES6 has revolutionized the programming language, adding new features that make the language better suited to handling a variety of cases, especially after JavaScript can now be run on the server via Node.js.

For each JavaScript ECMAscript 6 (henceforth, referred to as ES6) features, I will be explaining exactly why I believe that the mentioned feature is a great addition to the language.

For now, I am going start off with 5 features (there are a few more that I want to add to the list, but those will come in the near future).

This post is meant to be a summary of what I think are the best parts of ES6 and a summary of why I think it is. Therefore, unlike most of my other posts, I will not be diving into the specific behavior, theory and idiosyncrasies of each of the features mentioned in this post.

For the aforementioned reason, I would like to point out that this is not a detailed guide on each of these new ES6 features.

Rather, it is a overview of what I think are the best features that were shipped in ES6.

If you are convinced that these features are well worth your time investigating, I lay out a list of recommended resources for you to go through.

These resources are hand picked and designed to direct you towards the best features of ES6 and also practical resources to help you understand and apply these new features in your code in as little time as possible.

If you disagree with some of the points and have recommended resources/advice that I should look into, please leave a comment and let me know. I plan on continuously updating the content so that the information here is relevant, resourceful and helpful. With your help, I am hoping to (in time), build this list into the most comprehensive list.

So, please feel free to contact me with suggestions on what to add, omit or change :). That would help me and all the other people who come across this post.

For each point however, I STRONGLY RECOMMEND that you apply your knowledge by actually writing code. Just as a writer becomes better at writing when they consistently write, programmers become better programmers by writing code.

If you want a detailed guides on one or all of these features, please let me know via the comments. I will be more than happy to write a separate detailed guide for each of these features.

Enjoy the read!

Arrow Function

Arrow functions have created a lot of hype in the JavaScript community when it was first introduced. Naturally, to those that are used to working with arrow functions, code will look much cleaner and compact.

Recently, lambda functions have becoming all the rage in the world of programming, with the rise in popularity of functional programming.

They provide a great way to write short, throw away, anonymous functions (functions without names) on the fly, which is often seen in the word of JavaScript programming, even more so after the introduction of ES5.1, which introduced more functional programming friendly features.

It was only a matter of time before lambda expression support was added to the language.

For example, lets take a look at a simple operation.

var addOne = [1,2,3].map(function(val) {
    return val + 1;
});

Here is the same code reproduced using arrow functions.

var addOne = [1,2,3].map(num => num + 1);

By comparing the two, you may notice the following points

  • In the arrow function, the return keyword was omitted.
  • There was no parenthesis surrounding the parameter num prior to the =>. In another words, we didn’t need to do the following: ((num) => num + 1);

Yes, in this case, the arrow function does make the code shorter and more concise.

As mentioned previously, arrow functions are anonymous functions.

In another words, the following functions are similar.

var log = function(item) { 
    console.log(item); 
};
// similar
var logArrow = item => console.log(item);

I said similar, because there are some subtle differences, which we will go through briefly in the next sub-section.

Difference between arrow functions and traditional JavaScript functions

I may receive a lot of backlash from saying this, but I am going speak my mind anyway. Personally, I am strongly against using arrow functions blindly everywhere in our code.

In my personal opinion, arrow functions are NOT the new way of creating functions. In another words, I strongly feel that arrow functions should not entirely replace the function keyword.

To summarize my main argument for the aforementioned statement, it is because the arrow function is not syntactic sugar. To further elaborate, there are cases where arrow functions and functions declared with the function keyword behave differently.

Let me provide an example with two words: this keyword.

Therefore, while it is a great way to make certain subroutines more readable, compulsive usage can later lead to confusing, difficult to debug code. And no developer enjoys working with a buggy code base, unless they want a workout or a massive headache. This leads us into the next sub-section.

Because this is not meant to be a in depth tutorial, but an overview of the best features in JavaScript, I am going to list the difference in bullet points.

Below the list, I will also provide recommended readings that will get you up to shape on some of the difference, as well as providing more detail and contextual information.

  1. Lexical this and arguments. Arrow functions do not have their own this or arguments binding.
  2. Arrow functions cannot be called with the new keyword.

source: stackoverflow

Recommended Readings

Here is a list of recommended readings to get up to speed on arrow functions.

const keyword

If you have a C family programming background (C, C++, C#, etc.), const will feel awfully familiar. The const keyword makes the data stored in a particular location in memory immutable. The particular location in memory is very important.

Prior to the introduction of const, there was no way to guarantee that a value type’s value will not be changed during run time, thus leading to unexpected bugs and side-effects if an application was coded poorly.

With the introduction of const, we are finally able to potentially reduce the number of possible side-effects by declaring constant variable with the const keyword.

Basic Use Cases and Gotchas

Let me demonstrate the importance via an example.

var aNum = 8;
const CANT_CHANGE_ME = 10;
CANT_CHANGE_ME = 8;               // error
CANT_CHANGE_ME = aNum;            // Also an error: See behavior of value types

If we run the code snippet, we will see the following error on the console.

Uncaught TypeError: Assignment to constant variable.

Ultimately, the reason why I love the introduction of the const keyword in ES6 is that using const creates code that is more readable and predictable if used correctly.

People who are not too familiar with reference values may be confused by the const keyword, which will result in const being misused and also resulting in unexpected results. I will not be going into details, but I felt that it was important to address this briefly in this post.

If you want to read about reference vs value types, please pause for a moment and take time to read before proceeding.

Let us examine a short code snippet.

const PERSON = {
    name: "Jay",
    age: 1337
};

PERSON.name = "Jay";            // Will this work?
PERSON = {};

If you try running the code above, the following line

PERSON.name = "Jay";

will work. However, if you try to run

PERSON = {};

you will get the following error.

Uncaught TypeError: Assignment to constant variable.

But wait, I thought const made the following object immutable???

Remember when I said that it makes the data stored in a particular memory location immutable? The particular memory location is the important part in the definition.

In another words, you can change the properties of an object, such as PERSON.name, but you cannot change the location in memory that var PERSONis pointing at. Therefore, we get an error when we try to PERSON point to a fresh new object.

In a nutshell, the data stored in a particular memory location is mutable, but its properties can be mutated.

Recommended Readings

Although the const keyword is fairly straight forward, the difference between simply knowing what it does and knowing how to use it properly can make a lot of difference.

The readings suggested here is designed to take you from simply knowing what it does to actually identifying cases where it is appropriate to use the const keyword to define a variable.

let keyword

The let keyword declares a block-scoped variable. For those that were not used to variable scope and hoisting in JavaScript, this feature is an answer to prayers. It removes some of the predictable, obscure side-effects caused by hoisting in JavaScript, resulting in more predictable results.

Personally, I think it is definitely one of the best parts of ES6 and a great addition to the JavaScript language.

Why? Because now we have block-scoped variables, which will remove some of the confusion with variable hosting. I know I mentioned this three times in a row, but I think it is that important.

Let us look at a simple code snippet example.

function jsHasFunctionScope() {
    if (true) {
        var preES6 = "This is VAR!";
        let letIsCool = 5;
    }
    console.log(preES6);    // "This is VAR!";
    console.log(letIsCool); // Error
}
jsHasFunctionScope();

As you can see, letIsCool is no longer in scope, since it was declared inside of the if statement block. If you try running the code above, you will run into the following error.

Uncaught ReferenceError: letIsCool is not defined

In contrast, preES6, though it was declared inside of the if statement still logs out “This is VAR!” because the var keyword creates variables that are function scoped.

Try logging preES6 outside of jsHasFunctionScope. The following will be outputted onto the console on the google chrome console screen.

"This is VAR!"

Recommended Readings

The let keyword is fairly forward, so you won’t have to do too much reading.

Spread Operator

This feature is seriously an amazing addition to JavaScript.

To demonstrate its awesomeness, let me show you an example.

function printStudentInfo(name, age, classCode) {
    console.log("name: " + name  + ", age: " + age + ", class: " + classCode);
}
var  name = "Jay",
      age = 10,
classCode = "10C";

// Without spread operator
printStudentInfo(name, age, classCode);

var args = [name, age, classCode];
printStudentInfo.apply(null, args);

// With spread operator
printStudentInfo(... args);

As you can see, with the spread operator, there is no need to use the built-in apply() method, which forces you to sometimes perform unnecessary steps such as passing null as the this value into apply().

For more information, I recommend checking out the following post which examines six great uses of the spread operator.

Recommended Readings

Aside from the article about the six different ways of using the spread operator, here are some other additional resources to get you up and running with using the spread and rest operator.

Promises

Ever heard of callback hell? Chances are, if you have been writing code in JavaScript for some by (at least 2-3 years), you will have come across this turn. Callback hell, is not called callback hell because of the ugly pyramid shape code, but rather, due to the unpredictability in the sequence of logic processed, as a result of failing to manage the order and state of the asynchronous operations.

Kyle Simpson, author of the popular and highly recommended JavaScript series you don’t know JS provides a great example of what callback hell is.

“callback hell” actually has almost nothing to do with the nesting/indentation. It’s a far deeper problem than that.

For more information on callback hell, I suggest reading on Async and performance by Kyle Simpson. Trust me, this is well worth your time. Plus, Kyle does a way better job at explaining this than I ever can.

Why am I mentioning callback hell? Because …

Promises are ES6’s answer to callback hell.

To provide a brief illustration of what promises are, think of placing an order at a local pizza store for some delicious pepperoni pizza. You pay for the pizza, they will give you a ticket with your order number and what you ordered. Once the pizza is ready, you can exchange that ticket (or token) for the actual pizza. Afterwards, you can be well on your merry way with your delicious pizza, free to do whatever you want with it.

IMPORTANT: with async await being added to ES 2017, the days of promises may be fairly short. However, it is nevertheless a good part of ES6 as it did alleviate a lot of the pain surrounding asynchronous programming prior to ES6.

Furthermore, understanding how promises work will help you work with the new async await feature in ES 2017.

I do recommend checking out the following post on Six Reasons Why JavaScript’s Async/Await Blows Promises Away.

Recommended Readings

You may notice that some of the contents below overlap. The reason why I am posting multiple links is so that you are able to read the same concept in a variety of styles and forms.

Promises

async await

Default Parameters

Default parameters have definitely made JavaScript code that apply the concept of default parameters much more readable (for both newcomers and veterans alike).

This is better explained with code.

function delayedNotification(milliseconds, message) {
  
    // Pre ES6 way of setting default parameters
    millisecond = milliseconds || 5000;
    message = message || "You didn't set a message numb nuts!";

    setTimeout(function() {
        if (message) {
            alert(message);
        } else {
            console.log(message);
        }
    }, milliseconds)
}

As you can see, the pre ES6 way of writing this code is quite ugly and somewhat confusing, especially for developers that are not too familiar with JS.

With ES6 default parameters, the default values are set like this.

function delayedNotification(milliseconds = 5000, 
                     message = "You didn't set a message numb nuts!") {
    // Write your logic here.
}

Instead of having to look inside the body of the function to see if any default values are set, we only need to look at the arguments.

This also results in less unexpected behavior and more predictable results.

This addition is more in line with the natural thought process of human beings (reading and processing from left to right, top to bottom) and thus is a great improvement to readability.

Recommended Readings

Albeit the default parameters are fairly straightforward, it may take some time to get used to using it in your code, and also to be fully aware of some caveats. Here are some recommended readings that will get you up to speed with this feature.

Bonus: const, let and var

Okay, before ending this post, I want to tackle this ongoing controversial topic.

As you know, these keywords are used to initialize and store values in memory (or variables). There is a whole witch-hunt about stating that let is the new var, and whatnot.

But please, do be sober-minded when you do make a judgement. Just because somebody stated that let is the new var, don’t blindly jump the bandwagon.

I admit that the cases for replacing var with let are fairly strong, as variable scopes and hoisting have been one of the primary causes of side-effects in JavaScript.

However, there are some cases where using var makes more sense.

First of all, let us start off by asking the following question.

What does the word let mean?

I am not sure how much of high school maths you remember. Does the following line ring a bell?

Let variables x and y represent two non-negative numbers. Source: Solution to Maximum/Minimum problems

Let is often used when solving algebraic problems. It is used for solving a specific, individual algebraic solution. Therefore, I think let should only be used in cases where the value is used once and does not need to be used again/recycled. This is of course my personal opinion, so please feel free to disagree.

In the next sub-section, I will try to prove my case with some examples where it makes more sense to use var.

Please feel free to disagree if this does not sit well with you. The purpose of this post is to not only share my opinion, but also to provoke discussions and critical thinking.

If you disagree, I would like to hear your reasons, in order to learn, grow and widen my own perspective. Hopefully, by discussing, you too will also benefit from it. Please leave a comment and I will respond as soon as I can.

Critical thinking – when should const, let and var be used?

As I mentioned earlier on, this is purely my opinion. Feel free to disagree. I will list my thought process below.

var

a shortened version of the word variable. The word variable suggests that the value stored in a variable should and will likely change.

let

As I mentioned in the previous section, I believe that the word let should be used to declare variables with a very temporary/short lifespan: I.e. a variable that is limited to the scope of the current problem.

const

Short for constant. According to dictionary.com, a constant is “not changing or varying”. Values assigned with const should not change and be constant throughout the program’s run-time.

As of now, because the primary target audience of the source we write is programmers aka humans, we should write in a manner that is easy for humans to read and understand. Imagine if you constantly change properties of a const variable without leaving any comments. I surely don’t want to be the developer having to debug the side-effects caused, especially if the code base is more than 10,000 lines.

I bet you that some developers who are unaware that the properties of the const variables are mutable and changing will be panicking when some nasty side effects occur during the run time of the program.

Recommended Readings

Unlike the answer to a mathematical equation, there is no absolute right or wrong answer here. Just make sure that when you declare a variable, that you are clearly communicating the intent, purpose and use-scope of the variable through the keyword used to declare that variable.

Conclusion

This post was a lot longer than I originally anticipated. I hope that it was a very invigorating and thought-provoking read.

Once again, if you would like detailed guides on each of these keywords, please let me know via the comments.

And if there is any points that I am missing, or features that should be added onto this list, please feel free to let me know and I will update this post accordingly.

Thanks for reading. Catch you next time!

About the Author Jay

I am a programmer currently living in Seoul, South Korea. I created this blog as an outlet to express what I know / have been learning in text form for retaining knowledge and also to hopefully help the wider community. I am passionate about data structures and algorithms. The back-end and databases is where my heart is at.

follow me on:
43 Shares