A summary of ECMAScript 6 features
github.com
github.com
Now if we can only get the bind operator [1] in a timely manner, everything will be awesome.
[1]: http://wiki.ecmascript.org/doku.php?id=strawman:bind_operato...
My first impression is that it's kind of confusing to read, but I suspect I'd get used to it.
Sort of similar to some of the destructuring assignment stuff, e.g. `let { address: { street } } = user;`. Awkward at first, but now I'm kind of into it – although I still think people are likely to abuse it.
Here's a good features comparison table of common transpilers: http://6to5.org/docs/compare/#comparison-to-other-transpiler...
There's no reason we'll have to wait for ES7. Seeing as how good 6 to 5 transpilers already are, I'm sure you'll be able to use await relatively soon.
I just feel like priority-wise, users would benefit most from modules (which made it), async/await, maybe class syntactic sugar, then everything else.
Then async/await is no solution for it either.
app.get('/thing', function (req, res) {
try {
await user = db.get({user: req.user});
res.send({user:user});
} catch {
res.send(400);
}
});
beats the hell out of: app.get('/thing', function (req, res) {
db.get({user: req.user}, function (err, user) {
if (err) return res.send(400);
res.send({user:user});
});
});
especially when you have conditionals or loops that can look like: if (user.name == 'abc') {
resp = 5;
} else {
await resp = db.get_resp({user:user});
}
await db.save(something);
I suppose it doesn't get rid of callbacks, just makes them readable.You are the one who stated generators were no solution to callback hell but async/await was, yet here's what your code looks like with generators:
app.get('/thing', function* (req, res) {
try {
let user = yield* db.get({user: req.user});
res.send({user: user});
} catch {
res.send(400);
}
});
... app.get('/thing', function (req, res) {
db.get({user: req.user}).done(user => {
res.send({user:user});
}, error => {
res.send(400);
});
});Also, Traceur got a patch in master for async generator functions earlier this week.
const map = (fn, [x, ...xs]) => (x === undefined) ? [] : [fn(x), ...map(fn, xs)];
This gives me the warm and fuzzies.Now there's a completely new function syntax that doesn't use parens and has different scope rules
var odds = evens.map(v => v + 1);
Enhanced object literals: // Computed (dynamic) property names
[ 'prop_' + (() => 42)() ]: 42
what?? So it uses parens if there are no params, but not otherwise?Template Strings:
`In JavaScript this is
not legal.`
Seriously another String delimiter? `Hello ${name}, how are you ${time}?`
Why aren't we just using #{} like everyone else? // Construct an HTTP request prefix is used to interpret the replacements and construction
GET`http://foo.org/bar?a=${a}&b=${b}...
What??Destructuring:
var [a, , b] = [1,2,3];
Is that seriously just whitespace and another comma?Splats (spreads?)
f(...[1,2,3]) == 6
... means destructure?This is not readable code:
let fibonacci = {
[Symbol.iterator]() {
let pre = 0, cur = 1;
return {
next() {
[pre, cur] = [cur, pre + cur];
return { done: false, value: cur }
}
}
}
}
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
print(n);
}
Symbols without a literal syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Jesus Christ.Unicode:
"𠮷".length == 2
Awesome, still wrong.Modules are cool. Promises are cool. Tail call optimization is cool.
This is not readable code:
// Proxying a normal object
var target = {};
var handler = {
get: function (receiver, name) {
return `Hello, ${name}!`;
}
};
var p = new Proxy(target, handler);
p.world === 'Hello, world!';
ES6 is a mess. Javascript just got harder. var odds = evens.map(v => v + 1);
Is about as readable as it gets (inspired by C#, Java8, CoffeeScript), as a benefit of succinct syntax sugar we get intuitive `this` binding - i.e. pit of success. [ 'prop_' + (() => 42)() ]: 42
> what?? So it uses parens if there are no params, but not otherwise?Again not surprising, a leading `=>` would be a syntax error so `()` is an obvious compromise which can be naturally be extended to add args, e.g:
evens.map((v) => v + 1)
> Seriously another String delimiter? `Hello ${name}, how are you ${time}?`
Yep, String interpolation is incredibly useful especially in JavaScript which does a lot of string munging - this will lead to more succinct, readable code. Should be obvious why they didn't want to break existing JS by re-using "" double-quotes.> Why aren't we just using #{} like everyone else?
Who's everyone else (Ruby inspired langs)? Scala uses ${1 + 1} or $var shorthand (same as Groovy, Kotlin, JSP EL, Haxe), C# 6 uses {var}, Swift uses \(var) whilst Python and Java have string formats that use %(var)
var [a, , b] = [1,2,3];
> Is that seriously just whitespace and another comma?It's clearly ignoring matching the second element. Some languages choose to use `_` as a special ignore placeholder, JavaScript chose not to. Either way is not unintuitive with what it does so that's ok.
The other features are extremely useful if you need them, otherwise you can happily ignore them and use the subset you're comfortable with.
> Splats (spreads?)
> f(...[1,2,3]) == 6
> ... means destructure?
No, it means something very close to "apply" or "concat", depending on the usage. That example is the same as: f.apply(this, [1,2,3])
But it's cleaner syntax. The interesting part is that you can mix them in anywhere: function f(x, y, z) {
return x + y + z;
}
a = [1,2];
b = [3];
[...a, ...b] == [].concat(a,b) == [1,2,3]
[0, ...a, 4, 5, ...b, 6] == [].concat([0],a,[4,5],b,[6]) == [0,1,2,4,5,3,6]
f(...a, ...b) == 6
f(1, 2, ...b) == 6
f(...a, 3) == 6
f(...b, 0, ...b) == 6
> ES6 is a mess. Javascript just got harder.Want some cheese with that whine? It got more complicated, yes. But I'm liking most of the changes, personally. A lot. Most of them are long overdue.
BTW, if you open Firefox's console, you can try out many examples. Firefox already supports tons of ES6.
let fibonacci = {
[Symbol.iterator]() {
let pre = 0, cur = 1;
return {
next() {
[pre, cur] = [cur, pre + cur];
return { done: false, value: cur }
}
}
}
}
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
print(n);
}
I love how the only comment is explaining what "if (n > 1000) break;" doesParams are only optional if there is a single parameter.
* Tagged template strings might have some potential to be abused in interesting ways, since it looks like the tag function doesn't actually have to return a string.
* The Object destructuring/enhanced literals (and the Object rest/spread proposal in ES7) still take a lot of mental energy for me to parse. I'm worried they could be a maintenance liability in large projects, but that remains to be seen.
* Async functions/generators in ES7 will probably take a while to get used to, as well, but I felt the same way about Promises when they were first introduced, and they didn't turn out to be too bad. I don't have an issue with normal Promises/generators, so this might just be a matter of me needing to see the async stuff as a whole instead of the sum of its parts.
This was a pretty explicit goal, what they called 'paving the cow path'
JavaScript is a mainstream language. That means average people like myself can be very productive with it. It is easy to learn and it's easy to find people who can maintain JS code.
But it seems you need to be an academic in programming languages just to figure out what these new features do, and why they are needed. I'm afraid that the rapid development will make it harder to learn the language. And will introduce a lot of pitfalls and edge cases.
Or maybe I'm just afraid of change!?
- ridiculously verbose syntax for anonymous functions
- lack of a module system
- no string interpolation (seriously!)
- no block scoping - super annoying
- lack of language level support for immutability
- clumsy 'this' management
- clumsy variadic functions
- competing promise implementations
- competing and poorly interoperating class implementations
... And so on. This is a huge step forward and it should help redefine Javascript coding style in a much better way. My only complaint is that they didn't deprecate poorly designed features of the past.
a) Don't use anonymous functions ... You want your program to be easy to understand, so come up with a name for the function and put it as a sub-function at the bottom of the current function.
b) I love the Nodejs implementation of modules and I would say it's the main reason behind Nodejs success. But it doesn't make sense in the HTTP world. Imagine having to download 100 dependency files each time you visit a webpage.
c) I have a keyboard macro for " + + ". So if you don't save an extra keystroke, what's the deal? It might be useful if you have nasty habits like building HTML or SQL by concatenating strings though. (don't do that).
d) Just declare your variables at the top of the function and stop worrying about scope, (while listening to Bobby McFerrin.)
e) I can somewhat agree here. But where it's really needed you should make a copy or clone function. And if it's not really needed you shouldn't. Makes you write less complicated code because of laziness.
f) Give it a name!
function Car() {var car = this;}
Or if you don't want people to understand your code: var that = this;
g) You are probably trying to make your function do too much! If you Do want to have one function to rule them all, pass an object to it.h) It's possible to make async code intuitive. Stop using anonymous functions will help a lot! But it's not That easy. Promises is just another (ineffective; it just threats the symptoms) paradigm to reason with async code.
i) We don't need classes. The prototype already work great. It might be hard to learn but once you understand it's brilliant! (I don't blame you if you never will, it's hard to learn an old dog to sit).
I encourage you to use the paradigms you believe in, and also to try different solutions, and think outside the box. But don't force certain paradigms by changing the language itself. One exception being Node.js where you are forced into making modules. (but some people are stubborn and use Browserify to circumvent it).
Many of your suggestions are just optimizing for the current state of JS instead of thinking about how to best leverage the many brilliant syntactic advances from throughout the industry. I guess there's no point in arguing. Change is coming, and people can keep writing super verbose JS if they like; I'll be writing code that more directly reflects the actual important logic.
var odds = evens.map(v => v + 1);
I would write this instead: var odds = increment(evens, n);
But it's never as simple as this, evens would probably be some sort of async object and you probably want to call another function once the "incrementation" has completed.The only thing => does is to make the syntax more complex (and ugly) by saving a few keystrokes. And even worse, it's a treatment for a symptom from anonymous functions, that you shouldn't even use in the first place. And will be used everywhere, because we are lazy. But the time saved, will have to be used for mind juggling, to figure out what goes where in the syntax.
That said, I don't think all new stuff is useless. For example Object.defineProperty (ES5) that actually Adds to the language, and makes it possible to do things you couldn't do before. Like defining a set function.
const vals = ['#hp','#mp','#gp'].map(x => $(x).val());
And this: var elems = ['#hp','#mp','#gp'];
var getVal = function (x) { return $(x).val() };
var mtVals = [];
for (var x = 0; x < elems.length; x++) {
mtVals.push(getVal(elems[x]));
}
... then maybe you should actually go read some of those programming books you're so dismissive of.(basically just juggling data, you should make a real world example.)
I have seen Jquery before so I know $ returns a document element. And if you pass # into it, it will return getElementById(). And .val() returns .value
So my guess is that you want to get the values of hp, mp, gp, whatever that is. I don't understand why you want them in an array though!? Wouldn't it be better to store them in an associative array? So that you don't have to remember what position in the array points to what value.
Try this instead:
var signupForm = getFormData("signupForm");
alert( "Your name is " + signupForm["name"] );
Or without the abstraction: var name = document.getElementById("name").value;
A little more characters to type, but you don't have to learn a framework to know what it does. A trick here is to use keyboard macros to do the boilerplate. Don't var PI = Math.PI because of laziness.Yes, I can see my preceding correspondent was correct in discontinuing this engagement. Sorry to have wasted our collective time.
If it's too long to type, and you use it often, make a macro for it. When naming stuff, keep it short and simple though.
Also, you shouldn't hide logic behind names. I was actually wrong about evens.map(v => v + 1); If that's what you want to do, then write that. It's a thin line though, it might be hard to know what "v" is in that context.
Then he was invited to London. Where he met C, C++ and Java, who made him become ECMAScript.
Getting it to play nicely with my code coverage tool was a bit tricky, but aside from that it wasn't bad at all.
Bear in mind that ES6 is fully backwards-compatible with ES5, so you can set up a transpiler without having to actually rewrite your whole codebase right off the bat. It's pretty easy to upgrade gradually if you need or want to.
* Skinny arrows as a shorthand for functions (for methods and constructors that don't get 'this' from outside.
* Rest parameters with trailing arguments, e.g.:
function zip (...xs, f) { ... }
Seems like an oversight but I'm sure there was a reason (anyone care to comment?)...I guess arguments parsing isn't quite dead...
The problem with symbols is the absence of symbol literal syntax(along with the fact that one can access symbols through reflection).
For me the most important thing is: what was the first version to support this feature. So I know I can actually use it -- comparing to my users' browser usage stats.
samplestitch.com.s3-website-us-east-1.amazonaws.com
`let` in function scope is the same as `var`, in block scope it's narrow, it's basically the thing you want. `var` couldn't change, though, it would have broken existing code - hence `let`/