10 ms·
ES6 Cheatsheet
- deleted 11y ago[deleted]
- diezge 11y agoNot at work, but I use either ES6 or Typescript personally. "All of the syntactic sugar stuff changes the look and feel of the language too much for my tastes." I think it brings it into line with how the language is being used in production these days. Modules, generators etc make the language more beautiful, powerful and easier to maintain.
- at-fates-hands 11y ago>>> Not at work, but I use either ES6 or Typescript personally. Not a JS developer, but most of my friends who are have been transitioning to Typescript. The road is bumpy, but they say once you get some syntax stuff down, you're good.
- hockeybias 11y agoDitto.
- DCoder 11y agoTypeScript is very nice. The one main problem it has is lack of type definitions for third-party modules, some developers find having to "waste time" writing those defs themselves to be quite bothersome.
- CuriouslyC 11y agoTypescript gives you an "out" to type checking using the any type. Additionally, most libraries really worth using have .d.ts files floating around the internet somewhere, in DefinitelyTyped or otherwise.
- DCoder 11y agoThat's all true. It's a chicken-and-egg problem there, though. I've seen several arguments that the language is not worth looking into until more typings become available, and of course those naysayers are not going to write the missing typings.
- mercurial 11y agoWriting ES6 at work, turned into ES5 by Babel. I don't want to write "var self = this" ever again. Also, quite a few Node modules are ES6, and we use NPM for managing our frontend JS packages.
- s992 11y agoI'm still writing ES5 at work, but I've fully embraced ES6 (and bits of ES7) for personal projects. I love it and it's a major improvement to the language IMO.
- dexwiz 11y agoWebpack/browserify remove/polyfill most of the ES6 syntax so it is backwards compatible for browsers. Server side you just need to be aware of your engine's support of ES6. The extra syntax around arguments (defaults and rest) is useful. ES5 does support function overload, but often ends up some hard to read hacks. Libraries commonly have only a few functions, but the functions have flexible signatures. So the first thing you see when trying to read their source is a jumble of argument parsing. That said, ES6 can end up with some poor performance. For example, template literals are almost 10x slower than just plain string concatenation. But if you are concerned with performance, writing JS may not the be the best choice.
- mercer 11y agoI'm all in on ES6 when it's practical or allowed. Arrow functions are wonderful, I love destructuring assignment, const and let, and considering that some projects I work on involve a lot of async stuff, I'm close to just giving in and using ES7's async/await functionality. But most of the time this is in the context of Node.js development, and in every case I use Babel.js to turn the end result into ES5 code. I'm perfectly comfortable with using ES5, because as a freelancer/contractor I often have to do so. But I really miss the ES6 stuff and the more I use it, the more time it takes me to 'switch' to a mindset where I'm only allowed to use ES5 functionality. Nonetheless, it strikes me as really odd to actively prefer ES5. Having worked with Ruby and Python (among others), ES5 feels limiting for no good reason. The only rationale I can think of for prefering ES5 is nostalgia. Could you elaborate why you don't like the 'perl/python' style changes? Because I truly do not understand why one would choose to limit oneself to things like .bind(this) instead of the different forms of arrow functions that make functional-like programming so much easier. And I've found that the best part of JS is that it's decently functional. Edit: I would agree when it comes to the new 'class' keyword though. I'm not a fan of that.
- alistproducer2 11y ago> Could you elaborate why you don't like the 'perl/python' style changes? It's really just a style preference. I enjoy the "look" of C-family code. >why one would choose to limit oneself to things like .bind(this) I know 'this' is a source of pain for a lot of people. For me, I see it a source of flexibility. I've found the ability to control the context at will to be a huge benefit. It's a feature I miss when I'm writing in other languages.
- mercer 11y ago> For me, I see it a source of flexibility. I've found the ability to control the context at will to be a huge benefit. It's a feature I miss when I'm writing in other languages. But that's why you can still use the regular functions... I don't quite understand how having the added option of a more concise syntax with automatic binding to the surrounding context is less flexible. I often find myself using the regular function declarations to differentiate between different sorts of functions. The arrow notation is opt-in. Or is your issue that when you work with other people's codebases, you have no option to opt-out?
- rhinoceraptor 11y agoTemplate strings, arrow functions and object shorthand ({ foo: foo } === { foo }) are very nice.
- tlrobinson 11y agoTo be clear, that statement doesn't actually evaluate to true, but those two object literals are equivalent (not referentially equal)
- tlrobinson 11y agoWhy did someone downvote this? It's correct: https://babeljs.io/repl/#?experimental=true&evaluate=true&loose=false&spec=false&playground=false&code=let%20foo%20%3D%201%3B%0Aalert(%7B%20foo%3A%20foo%20%7D%20%3D%3D%3D%20%7B%20foo%20%7D) https://babeljs.io/repl/#?experimental=true&evaluate=true&lo...
- jxm262 11y agoI'm fully using es6 for most of projects now. Started about 2 months ago and will make all new projects I have with it. Import/export, destructuring, templates, string interpolation.. it just cuts down on alot of the cruft (imo).
- deleted 11y ago[deleted]
- tlrobinson 11y agoI'm also all-in on ES6. We use it extensively on Metabase (https://github.com/metabase/metabase https://github.com/metabase/metabase)
- ashearer 11y agoI prefer ES6/ES2015 (currently via Babel, and considering TypeScript). The let keyword and arrow functions in particular make it a much more pleasant language to work with than plain JS. It's now competitive with CoffeeScript, but with more coherent and predictable parsing rules.
- lukebennett 11y agoUsing ES6 here most of the time as well, there's very few reasons not to these days. Some of the changes may only be syntactic sugar but you very quickly find yourself not wanting to go back.
- igravious 11y agoThe only thing from this list of new ES6 idioms that doesn't sit comfortably with me is the short-hand for creating classes. I remember being kind of blown away way back in the day with the prototypical/functional nature of Javascript and how you could wrangle something into being that behaved in an object-oriented manner just like other languages that had explicit class declaration and object instantiation. Part of me feels that obscuring Javascript's roots in this respect is very un-Javascript-y. What think ye? Coming from Ruby, loving template literals, feel right at home with them, I wish even C could have them (if that makes any sense!).
- stared 11y agoIf "un-JavaScript-y" were a bad thing... JS is not a particularly pure, or well-designed, language, so we should not treat it religiously. Personally, I love ES6 for fixing many JS pain points (yes, hacky class-like object constructors are among them). If it is against it's history - so be it!
- khalilravanna 11y agoI think the cheatsheet does a great job of summarizing what makes me uncomfortable with es6 classes: >"...the syntax for creating classes in ES6 obscures how implementation and prototypes work under the hood..." Yes, it's great for if you're uncomfortable with prototypal inheritance and the "javascript way of doing things" (I'll maybe summarize that as composition over inheritance, mixins, knowing how to use call/apply etc.), but at the end of the day I'm worried it might be a crutch. Specifically, it might create the situation where a javascript noob might use es6 classes and never bother to learn how the prototypal chain works or all the myriad options available for mocking classes and OO behavior. That being said, maybe that's a shitty argument. When you have more tools in the toolbox there's always the option for someone picking the wrong tool. Does that mean you take the tool out? Or leave it because it is really useful when you know when to use it correctly. I imagine the latter.
- igravious 11y agoAgreed. And I meant prototypal, not prototypical :)
- krisdol 11y agoWow, var was so broken. Anyway, we use as much ES6 as Node 4 allows at work. Transpiling on the server never made much sense to me. I also used to sprinkle the fat-arrow syntax everywhere just because it looked nicer than anonymous functions, until I realized it prevented V8 from doing optimization, so I went back to function until that's sorted out (I don't like writing code that refers to `this` and never require binding, so while the syntax of => is concise, it is rarely used as a Function.bind replacement). Pretty much went through the same experience with template strings. Generator functions are great. I'm not a fan of the class keyword either, but to each their own. I think it obscures understanding of modules and prototypes just so that ex-Class-based OOP programmers can feel comfortable in JS, and I fear the quagmire of excessive inheritance and class extension that will follow with their code.
- zackify 11y agoAs of 5.4.0 arrow functions are more performant than binding, FYI: https://github.com/nodejs/node/pull/3622 https://github.com/nodejs/node/pull/3622
- krisdol 11y agoWoohoo! I've been hoping that this guy's Function.bind optimizations land before 6.0: http://benediktmeurer.de/2015/12/25/a-new-approach-to-function-prototype-bind/ http://benediktmeurer.de/2015/12/25/a-new-approach-to-functi... But you prompted me to check on the status of his work, and was happy to find a new post: http://benediktmeurer.de/2016/01/14/optimizing-bound-functions-further/ http://benediktmeurer.de/2016/01/14/optimizing-bound-functio... It looks like V8 will finally be able to inline bound functions (https://codereview.chromium.org/1581343002 https://codereview.chromium.org/1581343002)! That's huge!
- Rezo 11y agoTranspiling on the fly on the server is even more painless than for the frontend: - Require babel-core/register (as of Babel 6) - Require your server entry point ES6 file. - Done. Everything just seems to work, no need for sourcemaps or anything; line numbers, error reporting, non-ES6 modules, everything Just Works. Haven't had a single issue since starting to do this 4 months ago (knock on wood). Highly recommended!
- banku_brougham 11y agoMuch more than a cheat sheet, this is a revealing window into js development. Helpful!
- shogun21 11y agoTwo questions: what happens if you use ES6 standards in a browser that does not support it? And would it be wise to hold off adopting until all browsers support it?
- tonyonodi 11y agoYou'll get an errror :) (probably a syntax error) You don't need to hold off on using it but you should definitely use a compiler like Babel[1] to compile your ES6 code to ES3 for compatibility. [1] https://babeljs.io/ https://babeljs.io/
- mercer 11y agoShouldn't ES5 be god enough at this point (honest question)?
- SiVal 11y agoYes, in most cases. As always, the pro way to do it is to examine the browser statistics for your target market, decide which browsers you will/won't support, and build and test for those browsers. If you don't want to go to all that effort for your smaller project, the bottom line is that most developers today end up targeting ES5.
- Raphmedia 11y agoI would recommend taking a look at this page for a bigger "cheatsheet": https://github.com/lukehoban/es6features#readme https://github.com/lukehoban/es6features#readme
- TheAceOfHearts 11y agoThis cheatsheet is wrong about ES2015 modules. They don't define how module loading works, that's still being worked on [0]. ES2015 just defined the syntax. [0] https://github.com/whatwg/loader https://github.com/whatwg/loader
- jcoffland 11y agoGreat reference and overview of ES6. One minor quibble. I was bothered by the misuse of the words "lexical" and "interpolate". The lexical value of the keyword "this " is the string "this". Then, you might translate between two technologies such as CommonJS and ES6 but interpolating between them implies filling in missing data by averaging known values. Granted this word is commonly abused. Sorry this is a bit pedantic but these corrections would improve the document, IMO.
- wesleytodd 11y ago> By sticking to this paradigm, we make our code easily readable and allow ourselves to interpolate between CommonJS and ES6 modules. This sentence should probably say "interoperate"
- jcoffland 11y agoI believe you are right.
- overcast 11y agoString interpolation, classes, promises, and parameter stuffs. A tear rolls down my cheek.
- lukasm 11y agoIs there a similar thing for coffescript?
- grawlinson 11y agoLess and less people are using CoffeeScript due to ECMA2015/ES6 being released with the large majority of functionality that CoffeeScript was created for. You're probably better off just switching to ES6, but that's just my opinion.
- z3t4 11y ago"Require" is the reason why we now have a module for just about anything in Node.JS. I even think Kevin Dangoor or whoever invented it should get the Nobel prize. But then the ES committee choose to use paradigms from year 1970. I cry every time someone use import instead of require in JS because they miss out why globals are bad, modularity is good, and the JS API philosophy (super simple objects with (prototype) methods).
- tlrobinson 11y agoI'm not sure I understand. ES6 modules are basically equivalent to "require". `import foo from "foo";` is the same as `var foo = require("foo");` Yes, it was Kevin Dangoor who started the CommonJS (originally "ServerJS") project and led many of the discussions. Kris Kowal and many others were instrumental as well. This is probably the pivotal mailing list thread for what became CommonJS modules: https://groups.google.com/forum/#!topic/commonjs/Gr72Bc8Twzc https://groups.google.com/forum/#!topic/commonjs/Gr72Bc8Twzc I may have written the first implementation... https://github.com/tlrobinson/narwhal/commit/f960f7902fb90994e0081a1afe8ce6033e2639bc https://github.com/tlrobinson/narwhal/commit/f960f7902fb9099... (RIP Narwhal!)
- z3t4 11y agoThe main technical difference is that you can not have scoped imports. The main impact though, is that many will use a hammer on screws, meaning; people used to "other tools", can now do so (ES6: import, class, etc). While require teaches you to use the electrical screwdriver.
- tlrobinson 11y agoAre you saying you can't do function-scoped imports ("require" inside a function)? I rarely see that used and it's not available in any other language I can think of.
- z3t4 11y agoYes. It makes things so much simpler. Your program do not have to be complex! It can exist entirely of functions that do not depend on their outer scope. You can basically change everything around them and the function will still work the same. And you do not have to look outside the function to understand what it does. You only have to know about the standard objects witch in JavaScript (ES5) is Math, Date, JSON and Error. Everything else is "required" when needed.
- sectofloater 11y agoThis will likely get downvoted - but I have just realized how much I was underestimating the privilege of developing apps in Dart instead of JavaScript. Dart had none of the mentioned idiosyncrasies from day one, all the features, and has a lot of other stuff (like async/await, yield, mixins, etc) to offer. Its tooling is very simple and powerful, and the overall experience is really nice - when there is a problem, it's always in the logic of my code, and not things like some weird implicit conversions that are so common in JS land. I almost forgot how terrible JS is...
- pcwalton 11y ago> Unlike var, let and const statements are not hoisted to the top of their enclosing scope. No, let is hoisted to the top of the enclosing scope [1] ("temporal dead zone" notwithstanding). let, however, is not hoisted to the top of the enclosing function. [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- mercer 11y agoI'd say that makes you technically correct, but practically speaking, if using let before it's declared (assigned?), this temporal dead zone, results in an error, it's pretty much not hoisted in the way that most of us think of it. Or is there a use case that I'm not aware of where the hoisting is beneficial despite the temporal dead zone?
- pcwalton 11y agolet f = function() { ... g(); ... } let g = function() { ... f(); ... } f(); Works despite the temporal dead zone and depends on hoisting. This exact example is why hoisting was kept for let.
- mercer 11y agoInteresting. This kind of stuff makes me want to dive into the details of these kinds of choices, as I regularly wonder why languages designed are a certain way.
- kclay 11y agoThis will come in handy, thanks.
- jbeja 11y agoWho is in charge of ES6 design? Is awful.
- joshontheweb 11y agoIs there a resource that tells me which of these features are available in the latest stable Node version?
- DCoder 11y agohttps://kangax.github.io/compat-table/es6/#node5 https://kangax.github.io/compat-table/es6/#node5
- deckar01 11y agoIs "WeakMap" really the suggested way to implement private class properties? Using "this" as a key into a Map of private variables looks bizarre. I would rather keep my code concise than create a layer of obfuscation.
- pcwalton 11y agoIt was really hard to make truly private properties that couldn't be leaked in some way without WeakMap. If you don't need foolproof leakage, Symbols are a more convenient way to get most of the benefits of private properties. This is intentional: as I recall, the committee realized that WeakMap wasn't the most ergonomic solution and created Symbols as a more convenient, though less ironclad, alternative.
- mstade 11y agoAdditionally, symbols would have provided a neat way to implement private (and privately shared) properties, if they hadn't decided on adding the `getOwnPropertySymbols` function[1]. Bummer. [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- abustamam 11y agoI love how concise this is an handles a lot of "Gotchas" when working with ES6, but can we call a spade a spade and NOT call this a "cheatsheet?" I always imagine cheatsheets to be just that; something I can render on one sheet of paper. Printing the entire raw README text would take 4 pages (2 sheets, front and back). I think it would be better titled, "ES6 best practices" since I think that's a more accurate description of what it is.
- edem 11y ago[This](https://ponyfoo.com/articles/es6 https://ponyfoo.com/articles/es6) is also a very informative guide of ES6. I highly recommend perusing it.
- s84 11y agoDidn't realize arrow functions preserver this! Now using arrow functions.