DEV Community

loading...
Cover image for ES6 Mini Crash Course: How to Write Modern JavaScript

ES6 Mini Crash Course: How to Write Modern JavaScript

chrisachard profile image Chris Achard Originally published at twitter.com ใƒป3 min read

This was originally posted as a Twitter thread: https://twitter.com/chrisachard/status/1169223691122749440

Want to write javascript like a sane person?

๐Ÿ”ฅ Here's a mini crash course just for you ๐Ÿ”ฅ

ES6+ JavaScript can actually be FUN to write!

(codesandbox links at the end)

1.

var is dead. Don't use var. ๐Ÿ˜

(why? lexical scoping)

If the variable will CHANGE, use let

If the variable WON'T change, use const

var let const

2.

Arrow functions automatically bind this

So it will be what you think it should be 95% of the time

Arrow Functions

3.

If you leave the {} off of arrow functions, it returns automatically

You can leave the the () off around the params if there's only one

The different syntax can be a bit confusing - but you get used to it pretty fast

Arrow function types

4.

You can define default values for function arguments now.

Super handy! ๐ŸŽ‰

Default function arguments

5.

With destructuring assignment, you can pull out specific values from objects or arrays

Commonly used in function signatures too - now you can have named parameters! ๐ŸŽ‰๐ŸŽ‰

destructuring assignment

6.

There's a new syntax for exporting and importing modules

You can export a single default value, and as many named values as you want from a module

(notice the use of destructuring assignment to import named values!)

import export

7.

Get the "rest" of the values in an object or array with three dots ...

(AKA, the rest operator)

Rest operator

8.

Three dots can also be used to E-X-P-A-N-D an object or array into a new one

This is called the spread operator

(Yes - three dots is both rest and spread. They are different, though conceptually similar)

Spread operator

9.

Backticks can be used to wrap strings now, and are called "template literals"

Inside of backticks, you can use ${} to do string interpolation!

This is much easier than saying: "Hello " + name + "!"

Template Literals

10.

Most browsers now support these features natively! ๐ŸŽ‰

(except for IE ๐Ÿ˜)

Most of it works in node except for ES6 modules, but there's a way to fix that ๐Ÿ‘‡

ESM Fix in Node

11.

Ok, but WHY is ES6+ JS better?

  • let/const scoped correctly
  • () => {} binds this correctly
  • destructuring assignment, ...rest and spread saves a bunch of typing

In short: it removes the hacks, does what you think it should, and less typing means fewer bugs.

Woo! ๐ŸŽ‰

12.

Here's codesandbox links so you can explore:

var/let/const
https://codesandbox.io/s/es6-var-let-const-xz50k?fontsize=14

arrow functions
https://codesandbox.io/s/es6-arrow-function-gye29?fontsize=14

destructuring assignment
https://codesandbox.io/s/es6-destructuring-assignment-3cv3b?fontsize=14

import/export
https://codesandbox.io/s/es6-import-export-2q3px?fontsize=14

rest/spread & template literals
https://codesandbox.io/s/es6-rest-spread-template-literals-puli0?fontsize=14

ย 

This mini-crash-course was fun to write! I hope you enjoyed reading it ๐Ÿ˜

If you liked it, you can find more by:

Thanks for reading!

Discussion (24)

pic
Editor guide
Collapse
mvelezwhitesbs profile image
Miguel Velez-White

Chris, I was very impressed with your tutorial; but I was also quite dumbfounded. I'm basically a retread. I grew up in the era of mainframes, punch cards and COBOL. dBaseIII+ and IV reminded me how much I missed programming. However, I stayed on the admin/engineering track. Now we have DevOps (DevSecOps and DevNetOps in some places). I love the concept, but it's going to take a while before I can feel worthy enough to contribute anything. I thought that Javascript might be easy as I'd had a taste of JSON when I was doing PowerShell and .NET. You tutorial taught me alright. It taught me that I know NOTHING about javascript. I tried to follow along as best I could, but it was like trying to understand Integral Calculus again. Let's just say that I got my butt whooped and barely passed it all those years ago. Looks like I'm going to be sitting at the 'kiddies' table for a while as I try to learn these other dialects.

I love languages. I can even speak a few besides English. But right now, my heads filled with PowerShell, .NET, Terraform, Ansible, PowerCLI and so on. The further I get, the more I realize that I don't know and it can be frustrating; but at the end of the day, it really is still fun.

Do you by chance have a 'baby-primer' version of your class? I don't think that Javascript for Dummies could even help me right now. What I can relate to is your teaching style. You are a great communicator and your graphics for the examples are first rate. So I know that some day, I'll be able to understand your teachings a lot easier. For now, I'll take my dunce cap and go sit in the corner for a spell. Don't worry, I'm not giving up. It's all too much fun and if you and the community can be patient with a slowpoke like me, then I know that I'll make the grade - just a bit further down the road.

Meanwhile, if you ever need any help with VMware, or need a few virtual servers built somewhere, I offer my services gratis because I really want to learn from you.

LLAP,
Miguel (aka GulMiguel/Airwolf) :)

Collapse
chrisachard profile image
Chris Achard Author • Edited

Don't feel bad! I should have been more clear at the top that this is a good ES6 intro if you already know javascript. If you don't have much javascript experience yet, then a lot of this was probably quite confusing :)

I don't have a crash course for basic javascript yet - but I do have one planned! So you can look forward to that at some point.

One of the better resources I've found is a great free book called "Eloquent JavaScript": eloquentjavascript.net/ which is much more complete and beginner friendly.

This website (DEV) also has some great intro JS resources! You may have to search a bit to find them, but I know I've read some good ones here in the past.

I hope that helps some! Let me know if there's anything I can help with specifically, or if you're really stuck on something.

Oh! and the best advice I can give is to just play around! use codesandbox.io or codepen, and just start to experiment there and see how things go.

Good luck learning!

Collapse
georgecoldham profile image
George

Just remember that while you may be using const in a static context, it is still a mutable value.

Collapse
chrisachard profile image
Chris Achard Author

Yes, good point (I actually almost included a warning in there, but too many warnings and it would no longer be a "mini" crash course ๐Ÿ˜‚)

Here's a good example:

const myObject = { value: "abc" };
myObject.value = "123";
console.log(myObject); // {value: "123"}

So yes - if you really need immutability, then you have to use another library, like: github.com/immutable-js/immutable-js

Collapse
mbuvarp profile image
Magnus Buvarp • Edited

Quite late to the party here, but a cool thing to note regarding your point 5 is that you can also "selectively" deconstruct an array, that is, select only certain elements. Like this:

const array = [1, 2]
const [, second] = array
console.log(second) // 2

Or more advanced:

const array = [1, 2, 3, 4, 5, 6]
const [, second,, fourth,, sixth] = array
console.log(second, fourth, sixth) // 2 4 6
Collapse
chrisachard profile image
Chris Achard Author

Yes, definitely! You can also put an underscore in the places you don't care about... eg:

const array = [1, 2, 3, 4]
const [_, second] = array
console.log(second) // 2
Collapse
thepeoplesbourgeois profile image
Josh • Edited

This is a fantastic write-up of the core ES6 benefits! I just wanted to note that if performance is a concern for functions bound to this, then the handleEvent API carries infinitesimal overhead compared to the arrow function syntax and bind(this) calls within the constructor.

const clickCounter = {
  submit: 0,
  reset: 0,
  elements: {},

  // `this` will be `clickCounter`
  handleEvent({currentTarget, type}) {
    if (type === "click") {
      this.incrementClicks(currentTarget);
    }
  },

  // `this` will still be `clickCounter`!
  incrementClicks(currentTarget) {
    const {localName, type} = currentTarget;
    localName === "button" ? this[type]++ 
      : (this.elements[elTag(currentTarget)] || this.elements[elTag(currentTarget)] = 0)++;
  },

  elTag({localName, classList, id}) {return [
      localName,
      id ? `#${id}` : null,
      classList.length ? `.${[...classList].join(".")}` : null
    ].join("");
  }
}

// count ALL the clicks!!
document.addEventListener("click", clickCounter);
Collapse
mehdiraash profile image
Mehdi Raash • Edited

[...someVariable] it's actually spread attribute not operator.

As you know ... are called Spread Attributes which the name represents it allows an expression to be expanded.

var parts = ['two', 'three'];
var numbers = ['one', ...parts, 'four', 'five']; // ["one", "two", "three", "four", "five"]

And in this case(I'm gonna simplify it).

//just assume we have an object
โ€ฆ






Thanks for the recap
Collapse
olalonde profile image
Oli Lalonde

The term "spread attribute" is mostly used by React/JSX. Not that it really matters, but the most correct terminology would probably just be "spread syntax" (the ECMAScript spec only refers to it as "SpreadElement" in its grammar).

Collapse
chrisachard profile image
Chris Achard Author

Interesting... heh - so, on that page it's called all four of these things:

  • Spread attribute
  • Spread operator
  • Spread syntax
  • Spread notation

... and it seems to all refer to the same thing :)

I've also found "official" docs calling it at least three of those things ๐Ÿคฃ

Is there an actual "official, for real" source for what it's called?

Collapse
mehdiraash profile image
Mehdi Raash

I believe, operators need operand(s).

ECMA divided this topic to:

  1. Arithmetic Operators
  2. Comparison Operators
  3. Logical Operators
  4. Assignment Operators
  5. Conditional Operators
Thread Thread
chrisachard profile image
Chris Achard Author

Hm, interesting. Does the variable that the three dots are on not count as an operand? (I don't know what the formal definition is)

Thread Thread
mehdiraash profile image
Mehdi Raash

Somehow yes, but I think because this '...' thing introduced the time that syntactic sugar came up to JS so they tend to keep it as just helper syntax, some developers don't like it to be called as an operator because of other programming languages same debate.(some folks in this way would say one language has got more operators to another...:-))

Thread Thread
chrisachard profile image
Chris Achard Author

Got, it (I think :) ). Interesting! I wasn't aware of the debate over the "operator" word. Thanks :)

Collapse
pcrunn profile image
Alexander P.

I just switched back to var...

Collapse
dubst3pp4 profile image
Marc Hanisch

Great article except the usage of var. I would not discourage it, as let is limited to the scope of braces whereas var is limited to the scope of the current this (function) context. Both have strengths.

Collapse
hseritt profile image
Harlin Seritt

Thanks, Chris. Good to know about the esm. I've noticed most of this works fine with React in the browser but not so much (sometimes) with Node. Thanks again!

Collapse
chrisachard profile image
Chris Achard Author

Yep! There is also a solution that involves renaming files to .mjs and using --experimental-modules, but I find esm works really well in practice (and is easier)

Collapse
hseritt profile image
Harlin Seritt

Totally agree. This is much better. Keep 'em coming Chris :-)

Thread Thread
chrisachard profile image
Chris Achard Author

I plan to! Thanks ๐Ÿ˜„

Collapse
malagutti profile image
Anderson

Great article! Simple and useful, thank you!

Collapse
papidev profile image
Papidev

I enjoyed a lot Chris, thank you very much!
I needed a pocket reminder like that.

Collapse
chrisachard profile image
Chris Achard Author

You're welcome! I had a lot of fun making it - trying to distill such a large topic into small, bite-sized chunks :)

Collapse
nimit2801 profile image
Nimit Savant

Very Interesting I'll share this post in my community.