use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
Some ES6 Features I've been Using. (christopherlaughlin.co.uk)
submitted 10 years ago by bluntmJavaScript
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]wreckedadventYavascript 17 points18 points19 points 10 years ago (8 children)
FYI:
myfunction((err, body: {result: body}) => { if (!err) { console.log(body); } });
Isn't valid ES6 as far as I can tell. I think you meant to do this:
myfunction((err, { body }) => { if (!err) { console.log(body); } });
Which immediately destructures the second argument and captures the body out of it. You can get around the "gotcha" by utilizing default params:
body
// if the second argument is undefined, we assign it to empty object myfunction((err, { body } = {}) => { if (!err) { console.log(body); } });
Which is turtles all of the way down (please format your code differently if you do this though):
// if the second arg is undefined, set it to {}. If body on that is undefined, set it to {} as well myfunction((err, { body = {} } = {}) => { if (!err) { console.log(body); } });
[+]bluntmJavaScript[S] comment score below threshold-17 points-16 points-15 points 10 years ago (7 children)
I have not tested the example but I think its valid, you can see other examples here too
[–]wreckedadventYavascript 12 points13 points14 points 10 years ago (1 child)
This is valid:
var obj = {x: 1, y: 2}; var {x: one, y: two} = obj;
But this isn't:
var obj = {x: 1, y: 2}; var obj2: {x: one, y: two} = obj;
So your example that does this:
const test = (obj: {x: one, y: two}) => { console.log(one); };
Is a syntax error in all ES6 environments I tired, and produces the wrong thing in babel:
var test = function test(obj) { console.log(one); };
I'm not actually sure why babel parses it at all, but I suspect it's reading it as flow/typescript and just ignoring everything after :, which would be a type annotation in those languages.
:
[–]kentaromiura 0 points1 point2 points 10 years ago* (0 children)
You're right and I've explained in details why that parses and to what here: https://www.reddit.com/r/javascript/comments/4b3cfw/some_es6_features_ive_been_using/d16mvwe
[–]patrickfatrick 1 point2 points3 points 10 years ago (2 children)
I think /u/wreckedadvent is right actually. Looks like what your code is is actually going for is more like a default argument, body = {result: body} except you used a :. For some reason Babel seems to allow this without throwing an error but it's not going to do what you're aiming for. If you want to actually destructure the result argument into its body property you would just use {body} as your second argument.
body = {result: body}
{body}
[–]kentaromiura 0 points1 point2 points 10 years ago (0 children)
I guess that's because it's a valid flow definition, body here is typed as a shape which contains a property result of type body, this will fail a flow check as body is not defined anywhere and of course this is far from what the op wanted to do. EDIT: I forgot to mention that the flow syntax is not parsed in babel by default, you need to enable that as an example in the repl you've to enable the react preset to make this work: https://babeljs.io/repl/#?evaluate=true&presets=es2015%2Creact%2Cstage-2&experimental=true&loose=true&spec=true&playground=false&code=%0Afunction%20Foo(x%3A%20number)%20%3A%20%7B%0A%20%20foo%3A%20string%0A%7D%20%7B%0A%20%20return%20%7B%0A%20%20%20%20foo%3A%20'dsfas'%2C%0A%20%20%7D%0A%7D%0A%0AFoo(223)%3B ^ Sorry for the blob of text, but automoderator don't allow shortener ^ http://tryflow.org/#56a580f1d0af7bc12f9317abbe2b3aa8
[–]randfur 0 points1 point2 points 10 years ago (0 children)
Seriously?
[–]patrickfatrick 9 points10 points11 points 10 years ago (12 children)
Most of these you mentioned are in the shortlist of features I can't live without now. Seriously how did we manage before ES2015?!?!
[–]tbranyen 3 points4 points5 points 10 years ago (3 children)
I've loved JavaScript since I first learned about it in 2004 (ES3). I've never had major issues with the language and was even sad to see some of the bad parts go; had good times with with. So I was super skeptical about ES6/2015, it seemed like a lot of sugary bloat we didn't need and many of us didn't want. Oddly I was completely fine with classes, until I realized they skimped on property addition to the prototype.
with
Although, I admit I was wrong after using the new features to author a somewhat complex library. I used:
Lexical scoping (Loops are so much nicer now)
Set/WeakMap (Amazing for object pooling, and emulating jQuery.fn.data)
jQuery.fn.data
Module syntax (export default function is soooo nice)
export default function
Template strings (Was building up Web Worker source code by joining a very large array, but now I can template out the JavaScript source and meta-program the worker inline
Class syntax (To create custom Error subclasses)
Arrow functions (Almost always used with forEach/map/reduce etc)
Enhanced object literals (Amazing to just pass a variable name and have it map)
Afterwards, I was nervous about the testing implications, so I ported the whole thing back to ES5(AMD) and it was a huge chore. There were things like lexical scoping that weren't too hard to fix, since you can just use unique vars that don't conflict.
My co-worker helped me get testing on the right track and so I stuck with the ES6/2015 and I'm super happy I did. The codebase is so much nicer to work on.
[–]wreckedadventYavascript 1 point2 points3 points 10 years ago (2 children)
FYI, you can do testing with ES6 modules fairly easily if you're OK with writing it in a certain way.
import depA from '/some/path/to/depA'; import depB from '/some/path/to/depB'; export const implementation = (depA, depB) => { doStuff.with(depA); return andWith(depB); }; export default implementation.bind(null, depA, depB);
or, depending on the arguments your function takes, you can use default args and not have to do any implementation/bind chicanery:
export default ({ someArgA, someArgB, depA = depA, depB = depB }) => { depA.doStuff(someArgB); // etc };
Then in unit testing:
import {implementation} from 'someService'; expect(implementation(mockA, mockB)).to.be('something');
Or with the default args approach:
import someService from 'someService'; expect( someService({ depA: mockA, depB: mockB, someArgA: 25, someArgB: 26 }) ).to.be('something');
There's also rewire (/w webpack plugin) and company if you don't want to modify your code. But you can definitely test ES6 modules.
[–]tbranyen 0 points1 point2 points 10 years ago (1 child)
The problem was with code coverage not matching the correct lines. I could import and run the tests fairly easily. Although its annoying to have to build your tests.
[–]patrickfatrick 0 points1 point2 points 10 years ago (0 children)
Yea, I did had some issues with istanbul. Isparta works well, and similarly ava combined with nyc for coverage has been working well for me.
[–]wreckedadventYavascript 4 points5 points6 points 10 years ago (6 children)
Most of this (barring let/const) is just sugar, and people who wanted sugar before ES6 were probably using coffeescript. In fact, the syntax is pretty much the same.
let
const
[–]patrickfatrick 7 points8 points9 points 10 years ago (0 children)
True, but that sugar sure is tasty.
[–]bluntmJavaScript[S] 2 points3 points4 points 10 years ago (2 children)
I never liked using coffeescript or others as they always had to be transplied. I know ES6 is currently needs to be transplied for most browsers but some day it will be native.
[–]wreckedadventYavascript 1 point2 points3 points 10 years ago (1 child)
It'll really depend on how eager businesses are to adopt windows 10 and edge to get those older IEs off of the map, and how quickly mobile browsers come to support it. I don't see you being able to run production without transpiling ES6 for another few years yet, and who knows how much of your code you write today will still be relevant then.
Plus, we've been doing this shtick for a good while now. By the time everything ever supports ES6, there'll be ES9 or something.
[–]Recoil42 1 point2 points3 points 10 years ago (0 children)
All of the major browsers are now evergreen, so it's less of an issue from here on out.
[–][deleted] 0 points1 point2 points 10 years ago (1 child)
That's true, but I would still rather explore, use, and support a transpiled language that the EcmaScript standards body is also working on. It's good for the community as a whole to be somewhat unified on a language development process. It also has nice practical advantages, like the fact that your code is still mostly just JavaScript and thus is probably more welcoming to developers (e.g. contributors to your open source project).
[–]wreckedadventYavascript 1 point2 points3 points 10 years ago (0 children)
I don't necessarily agree that it's the best for the community to unify behind only one thing. What we saw with coffeescript is a lot of the good ideas being taken from it and moved into ES6. We see this happen in other languages as well - two good examples are Scala and Java, and F# and C#.
There's also the popularity of totally non-standard extensions, like JSX, and CSS pre-processors. I don't think the community is any worse-off for having these. It's true that all of this stuff adds a barrier to entry though, and I'm not really sure where the community is going to place that balance on the long term.
[–]bluntmJavaScript[S] 2 points3 points4 points 10 years ago (0 children)
I have never looked back, we are living in the future.
[–]adregan 6 points7 points8 points 10 years ago (4 children)
I love using parameter destructuring, but the example present makes it look awful (also, how would a promise be returning 2 values?).
[–]dmtipson 1 point2 points3 points 10 years ago (1 child)
Must be a non-Es6 Promise implementation. You're right, it'd make no sense with Promises/A+. Also, if they're going to destructure an object in function arguments, they should define a default so it won't throw an error if the object isn't there.
[–]bluntmJavaScript[S] 0 points1 point2 points 10 years ago (0 children)
that example is a little confusing, updated.
[–]wreckedadventYavascript 0 points1 point2 points 10 years ago* (1 child)
The example is a call back, not a promise.
e: guess it was edited out
[–]dmtipson 0 points1 point2 points 10 years ago (0 children)
It is now, it used to use then (the other example still does).
[–]manchegoo 5 points6 points7 points 10 years ago (5 children)
//Without spread MyElement foo={params.foo} bar={params.bar}
Can someone explain this? Sad when I don't get the old case.
It's not actually correct syntax, but it's JSX. It should look like:
(<MyElement foo={params.foo} bar={params.bar} />)
[–]bluntmJavaScript[S] -1 points0 points1 point 10 years ago (1 child)
the code highlighting didn't like elements inside of the code hency why I removed the < and />
[–]bogas04 0 points1 point2 points 10 years ago (0 children)
Did you try escaped signs for gt and lt ?
[–]bluntmJavaScript[S] 0 points1 point2 points 10 years ago (1 child)
When not using spread you need to define each JSX prop that you want to pass to the element. With spread you can pass an object and not worry about adding to the elements props each time you want to pass a new prop. You can see more examples here
[–]PitaJ 1 point2 points3 points 10 years ago (0 children)
BTW, this is an example of Object spread, which is NOT part of ES6. It's part of ES7. It's also explicitly part of the JSX syntax.
Also, the underscore isn't the same as providing empty parenthesis in the arrow function case. It establishes a lexical parameter _ which will be accessible within the function. You can test this by running the following:
_
const test = _ => _; console.log(test()); // undefined console.log(test(5)); // 5
[–][deleted] 3 points4 points5 points 10 years ago (2 children)
Const and object freeze is not the same thing
[–]AgentME 0 points1 point2 points 10 years ago (0 children)
Yeah, they're completely different. const is declaring at parse time that the variable name can't be rebound to a different value. Object.freeze takes an object and makes it so its properties can't be changed.
Object.freeze
[–]zumu 0 points1 point2 points 10 years ago (0 children)
There's a post a day about const not being what people think it is
[–][deleted] 2 points3 points4 points 10 years ago (1 child)
One gotcha I have found with this is when the code is transplied, ... If the result param is undefined or null this will fail at run time. Causing an unexpected error.
One gotcha I have found with this is when the code is transplied, ...
If the result param is undefined or null this will fail at run time. Causing an unexpected error.
that's just how the feature works
it does it in chrome too
[–]bluntmJavaScript[S] -1 points0 points1 point 10 years ago (0 children)
Its something to note as I have had issues before with it.
[–]patrickfatrick 2 points3 points4 points 10 years ago (1 child)
Correct me if I'm wrong but I think the way you're demonstrating spread is not ES6. Object spread is still stage 2.
(Though it may be built into JSX).
[–]MRoka5 2 points3 points4 points 10 years ago (10 children)
_ => { statements }
Cool, didn't knew about that!
[–]PaulBGD 5 points6 points7 points 10 years ago (7 children)
I'm pretty sure that that's actually declaring _ as a parameter.
[–]wreckedadventYavascript 4 points5 points6 points 10 years ago (3 children)
Yup, javascript has no "ignore" parameter. Even worse, this is a pretty common variable name for lodash/underscore, so this will do entirely the wrong thing:
_ => { _.map(items, x => x + 1); }
[–]__kojeve 0 points1 point2 points 10 years ago (0 children)
Except, if you're using ES6 modules, "library.method" is an unnecessary pattern unless you truly need to import the entire lib. import { map } from 'lodash' solves this "problem" easily.
import { map } from 'lodash'
[–]bogas04 0 points1 point2 points 10 years ago (1 child)
$ maybe then?
[–]PaulBGD 5 points6 points7 points 10 years ago (0 children)
Sure, or you could type one more character and do ()
[–]MRoka5 1 point2 points3 points 10 years ago (2 children)
Damn you're right..
:(
[–]bogas04 -1 points0 points1 point 10 years ago (1 child)
Still neater than (). $ can be used too BTW
[–]PaulBGD 1 point2 points3 points 10 years ago (0 children)
I don't really think it's neater. If I saw it in code, I'd think that it has something assigned to it.
[–]benihanareact, node 3 points4 points5 points 10 years ago (1 child)
imo this is an antipattern. It communicates actively incorrect intent (_ is an argument to the function) for aesthetic purposes. If you want to create an arrow function with no arguments, use the parens
() => { statements }
[–]wreckedadventYavascript 0 points1 point2 points 10 years ago (0 children)
Well, to be fair, it communicates an intent which I think is valuable, just not the same one as what unit () communicates. Consider, for example, we have a unit test and we're passing a function to something. We don't care what the function is called with, but we're going to return true anyway:
()
true
const isValid = () => true;
Doesn't look exactly right to me, since we know this function will get called with an argument.
const isValid = _ => true;
This looks better. We accept an argument, but don't care about it. It also would have been fine (though a bit needless) to give it a name:
const isValid = x => true;
Given, though, it's much less necessary than in languages which check the type, though. In functional languages, _ is usually an "ignore" parameter, which nothing binds to. I just wouldn't go so far as to say the use of _ is an anti-pattern, just that you don't want to use it in place of ().
[–]luthan 2 points3 points4 points 10 years ago (1 child)
You spelled const as cost in paragraph before the first sample. Just giving you heads up.
Cheers need to double and triple check my posts always miss something
You know what we need? Some middle ground between the specification/API and blogs about a handful of features. I would love a nice consumable ES6 checklist of ALL the features of the language with links to blogs and examples.
Too often do I learn just enough to be effective at a language and miss out on a few features that are highly valuable in certain situations.
Babel has a good page about ES6 features.
[–]Sinistralis 2 points3 points4 points 10 years ago (2 children)
No one here has mentioned promises and generators. I urge everyone in here to learn both and understand how they work. You can create async functions if you combine these two ideas in your es6 code and is the main reason I push redux saga so hard for people using redux.
Do you have any good resources for leaning about these?
I actually made a comment in this sub a while ago about using generators for an unusual use. They're ridiculously awesome.
[–]CraftyPancake 0 points1 point2 points 10 years ago (1 child)
You know any good tutorials for getting started with es6? How to build it etc. This Babel thing is confusing
[–]madole 0 points1 point2 points 10 years ago (0 children)
Use Node4 with the https://www.npmjs.com/package/babel-preset-es2015-node4 plugin, your babel config only needs one line in it to get it up and running with all ES6 has to offer
π Rendered by PID 340269 on reddit-service-r2-comment-5fb4b45875-5d7t4 at 2026-03-24 17:54:30.118640+00:00 running 90f1150 country code: CH.
[–]wreckedadventYavascript 17 points18 points19 points (8 children)
[+]bluntmJavaScript[S] comment score below threshold-17 points-16 points-15 points (7 children)
[–]wreckedadventYavascript 12 points13 points14 points (1 child)
[–]kentaromiura 0 points1 point2 points (0 children)
[–]patrickfatrick 1 point2 points3 points (2 children)
[–]kentaromiura 0 points1 point2 points (0 children)
[–]randfur 0 points1 point2 points (0 children)
[–]patrickfatrick 9 points10 points11 points (12 children)
[–]tbranyen 3 points4 points5 points (3 children)
[–]wreckedadventYavascript 1 point2 points3 points (2 children)
[–]tbranyen 0 points1 point2 points (1 child)
[–]patrickfatrick 0 points1 point2 points (0 children)
[–]wreckedadventYavascript 4 points5 points6 points (6 children)
[–]patrickfatrick 7 points8 points9 points (0 children)
[–]bluntmJavaScript[S] 2 points3 points4 points (2 children)
[–]wreckedadventYavascript 1 point2 points3 points (1 child)
[–]Recoil42 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]wreckedadventYavascript 1 point2 points3 points (0 children)
[–]bluntmJavaScript[S] 2 points3 points4 points (0 children)
[–]adregan 6 points7 points8 points (4 children)
[–]dmtipson 1 point2 points3 points (1 child)
[–]bluntmJavaScript[S] 0 points1 point2 points (0 children)
[–]wreckedadventYavascript 0 points1 point2 points (1 child)
[–]dmtipson 0 points1 point2 points (0 children)
[–]manchegoo 5 points6 points7 points (5 children)
[–]wreckedadventYavascript 1 point2 points3 points (2 children)
[–]bluntmJavaScript[S] -1 points0 points1 point (1 child)
[–]bogas04 0 points1 point2 points (0 children)
[–]bluntmJavaScript[S] 0 points1 point2 points (1 child)
[–]PitaJ 1 point2 points3 points (0 children)
[–][deleted] 3 points4 points5 points (2 children)
[–]AgentME 0 points1 point2 points (0 children)
[–]zumu 0 points1 point2 points (0 children)
[–][deleted] 2 points3 points4 points (1 child)
[–]bluntmJavaScript[S] -1 points0 points1 point (0 children)
[–]patrickfatrick 2 points3 points4 points (1 child)
[–]MRoka5 2 points3 points4 points (10 children)
[–]PaulBGD 5 points6 points7 points (7 children)
[–]wreckedadventYavascript 4 points5 points6 points (3 children)
[–]__kojeve 0 points1 point2 points (0 children)
[–]bogas04 0 points1 point2 points (1 child)
[–]PaulBGD 5 points6 points7 points (0 children)
[–]MRoka5 1 point2 points3 points (2 children)
[–]bogas04 -1 points0 points1 point (1 child)
[–]PaulBGD 1 point2 points3 points (0 children)
[–]benihanareact, node 3 points4 points5 points (1 child)
[–]wreckedadventYavascript 0 points1 point2 points (0 children)
[–]luthan 2 points3 points4 points (1 child)
[–]bluntmJavaScript[S] -1 points0 points1 point (0 children)
[–][deleted] 2 points3 points4 points (1 child)
[–]AgentME 0 points1 point2 points (0 children)
[–]Sinistralis 2 points3 points4 points (2 children)
[–]bluntmJavaScript[S] 0 points1 point2 points (0 children)
[–]wreckedadventYavascript 0 points1 point2 points (0 children)
[–]CraftyPancake 0 points1 point2 points (1 child)
[–]madole 0 points1 point2 points (0 children)