ES6 For Beginners

One of the main things that I’ve been afraid to incorporate into my code since the beginning of my experience at General Assembly is ES6, or ECMAScript 6. It is the newest “version” of Javascript and at first glance was very intimidating. I got used to declaring functions with the word “function.” All of a sudden I’m supposed to ditch that word and replace it using an arrow (=>). And “var” is now seemingly obsolete and supposed to be replaced by two new concepts, “const” and “let”. I’m just going to make it simple for beginners like myself to use a couple of the features of ES6 syntax by comparing the ES6 equivalents to the old ES5 ways of doing things. Here’s Chris…

Functions. It seems like I just got used to using functions in ES5, but I’m attempting to move on from my dinosaur status and use the new => syntax in my code. Writing functions in ES5 and before was fairly clunky compared to the way we write function in ES6. Instead of writing:

function() {
console.log('I'm old school');
}

… we can now write

() => { console.log('I'm no longer a dinosaur'); }

It doesn’t seem like much of a change at first but once you start adding in parameters or returning object literals ES6 will be blatantly neater and easier to read in your code.

Let’s talk about scope. Scope has always been a bit difficult for me to wrap my head around. In my opinion, ES6 doesn’t make scope easier to understand but it does add more functionality to coding in Javascript. Outside of a function, in the global scope, var and let work the same (with exception to the global window object). When used in a function var applies to the entire function, while let applies only to the block it belongs to. So what that means is that if you have a for loop inside of a function then let will only apply within that for loop, while var can still be used in the entire function. This gives a little bit more specificity to declaring variables in functions.

The other topic I want to talk about is the only feature of ES6 that didn’t scare me right off the bat. Template literals make combining strings and variables extremely easy compared concatenation. Let’s face it. Concatenation is an ugly word for an ugly chunk of code. Would you rather see:

'Hello, this is a ‘ + concatenation + ' and I am super ugly'

or:

'Hello, this is a ${templateLiteral} and I am super purdy'

By using this syntax, you don’t have to use plus signs broken up by quotation marks anymore and those nasty old concatenations go out the window. Wasn’t that easy?

Obviously, what I’ve described here doesn’t really even scratch the surface of what ES6 has to offer, but I hope this has helped beginners understand a little bit more of what’s going on when encountering the latest version of Javascript!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.