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
2.
Arrow functions automatically bind this
So it will be what you think it should be 95% of the time
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
4.
You can define default values for function arguments now.
Super handy! π
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! ππ
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!)
7.
Get the "rest" of the values in an object or array with three dots ...
(AKA, the 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)
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 + "!"
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 π
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:
- Following me on twitter: @chrisachard
- Joining the newsletter: chrisachard.com
Thanks for reading!