Most of it is just superfluous fluff that doesn't actually do anything but change the syntax to something they perceive as fundamentally better, when it's just a matter of taste and fashion.
Let's say I make a new language called javascript++.
Instead of having `function` be a keyword, I chose `functioooooooooooooooooooooooooooon`. Based on their syntaxes, do you find one fundamentally better?
function Person(){
this.age = 0;
setInterval(() => {
this.age++;
}, 1000);
}
and function Person(){
this.age = 0;
var my = this;
setInterval(function(){
my.age++;
}, 1000);
}
are barely visible, but the second one is actually legible. Why are we arrowing in nothing into curly braces? Oh, it's actually a function. Great. let names = persons.map(p => p.name);
Compared to ES5: var names = persons.map(function(p) { return p.name; });
The arrow syntaxes increases readability pretty much everywhere. Promises, for example: save(value)
.then(result => this.update(result))
.catch(err => Application.showError(err, "Could not save."))
(The use of a function in the "then" here is to avoid having to bind() the function; the alternative would be: .then(this.update.bind(this)).)Your setInterval example is a somewhat inappropriate example of the usefulness of arrows as it doesn't take any arguments and doesn't return anything (so you didn't need the braces).
But the fact that you have to alias "this" is a big argument in favour of arrow syntax. It may be trivial in a small example, but it's not trivial when extended to an entire app. You'll pretty much end up aliasing "this" in every single method. If you change any logic around, you'll end up having to either add new aliasing, or chase down unused alias variables, just to add/remove closures. (And what do you call that variable? Is it "this_" or "_this" or "self"? When working on a team you'll have to agree on a convention if the code is to remain readable.)
And your second example; I was going to re-write it, but then I realized I couldn't because I didn't know what `this` was. I don't think `this` is useful, and I try to avoid it because of its malleability and the confusion it often brings because of its overly dynamic nature.
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... , Ctrl-F for `Person` or something
Not sure why you don't know what "this" is in the second example. The whole point is that it's predictable. "this" is always the instance your method is defined in, unless you bind it to something else, which requires being explicit. I intentionally didn't include any context, but think about it this way:
class Store {
save(object) {
this.client.put("/objects", JSON.stringify(object))
.then(result => this.update(result))
.catch(err => Application.showError(err, "Could not save.")) }
}
}
"this" is extremely useful. I'm not sure how you could argue otherwise. Here's another pattern I use all the time: this._socket = new WebSocket(`ws://${url}`);
this._socket.onopen = () => {
this._state = 'connected';
this.emit('connected');
};
The lambda syntax allows placing logic lexically where it belongs. foo.bar()
then inside bar(), "this" is foo. Whereas if you do: quux(function() { console.log(this); })
...the "this" will point to whatever quux's "this" is, and it could be anything, depending on what quux() is doing. You can't depend on "this" being correct here.Hence people have for years used bind():
quux(function() { console.log(this); }.bind(this));
But this is neither nice to read (or write), nor is it performant. Many libraries, such as Underscore, also allow you to pass in a context variable: quux(function() { console.log(this); }, this);
This requires that quux() passes the context as the "this" argument to the function.The lambda (arrow) syntax fixes all of this [pun] by preserving "this" as a lexically scoped reference:
quux(() => console.log(this));However, in my opinion, repeating this many many times throughout a codebase is irritating to write, and adds extra weight and bug surface area to the code.
Therefore adding some syntax sugar to remove the need to do this, i.e. the first example, is a nice feature. I know opinions on syntax and formatting are pointless and endless, but could you please explain why, for you, is it less legible? Once you're used to it, don't you just scan () => as no-arg anon function signature the same way you scan function() as that now?
function Person() {
this.age = 0;
setInterval(this.incAge, 1000, this);
}
Person.prototype.incAge = function personIncAge(that) {
that.age += 1;
};
http://jsperf.com/bind-vs-closure-vs-paramThey're not expensive. You're not binding thousands of times a second anyway, so stop your silly premature optimizations.
2. You are making an assumption that you aren't binding thousands of times a second. You need to take actual use case into consideration.
3. My example has a 1000:1 method call to bind ratio and it's still a significant difference in benchmarks. Yes, it's that expensive it's important to think about in critical sections of code.
You don't know how much you're missing here. I wish that ECMAScript* considers adding support for "indented syntax" like in Sass to make it even more easier to read and go through the codebase without seeing all these ugly braces around.
*: or a white knight programmer volunteering to offer this functionality for us all :)
I just want the indentation without all the baggage that comes along with CoffeeScript.
Off the top of my head, other languages that are considering and implementing syntax extensions include Python (e.g. "yield from"), C# (e.g. "async/await"), and Java (lambda expressions).
I actually think that it's pretty low to accuse ECMAScript of "mangling" JS syntax when they are just trying to add modern extensions that make common patterns easier. Of course this function bind syntax is just a proposal and hasn't been accepted into the standard yet. But what about it bothers you so much? What about iterators or shorter function definitions, are those also nightmarish manglings of syntax? I mean, really. The usage of Javascript is evolving from simple embedded scripts to gigantic client/server applications. It's no surprise that the language itself will evolve as well.
I think the uncertainty around Javascript (and I do agree that there seems to be a real sense of confusion in the community when you look at the explosion of libraries and frameworks) is more related to the fact that we are trying to solve hard problems in a language that really gives us no help. We get no type checking, no good concurrency APIs, no immutability, no good sequence abstractions until iterators, just a fairly low-level and extremely hackable language with an unusual prototypal inheritance system.
Well, who knows. I would personally like to see some more stuff be standardized in the language or the official APIs so we don't end up with four competing libraries implementing "map" and "reduce", or promises, or whatever other thing.
The only difference with ES6+ is that the uncertainty will come from the addition of features people have complained were missing, instead of the traditional uncertainty that came from the intersection of its flexibility and dev's desire not to learn it.
I feel that hasn't changed over the years outside of more and more people not knowing how to use JavaScript (and more and more people who actually know their script).
items .filter(isOk) .map(toOtherType) ::flatten()
In C# that sort of case is primarily handled by extension methods. They have their issues not least in terms of collisions, but to me they are a beautiful solution. The equivalent in JS would seem to be the always unpopular choice of adding these methods to the prototype, and as with extension methods you'd want the user to opt-in to their addition (possibly at object level here?).
Not sure though, maybe I've missed something.
If you took the function bind syntax to its natural extreme, you end up with a model like Python or Nim, where all instance methods accept their "this" as a first parameter, and "a.call(b)" is equivalent to "call(a, b)". Personally I always thought that was a particularly elegant way of implementing instance methods, because it doesn't require inheritance or modifying the original type.
In Nim it even lets you do some very interesting method chaining to replace nested calls, like "toInt(sqrt(toFloat(num)))" can be equivalently written "num.toFloat.sqrt.toInt"
Not sure on the whole this as argument, I prefer it to the current approach of this being decided at framework/library level because I get bored of having to bind each function to get lexical scoping back. That Nim code is indeed beautiful though, maybe need to give ti a look ta.
> ...can also represent infinite sets
This is the highlight.
It's one thing to have to keep on top of the new frameworks springing up every five minutes - which you can, for the most part, ignore for at least six months until they start to gain some traction or have disappeared entirely - but when the core language itself is changing (and growing) at this rate, it really becomes an altogether more disconcerting and nightmarish proposition.