104 points · by caisah · 11y ago · 111 comments
>>> def f():
... type(x)
... x = 10
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'x' referenced before assignment
irb(main):010:0> def f()
irb(main):011:1> x.class
irb(main):012:1> x = 10
irb(main):013:1> end
=> nil
irb(main):014:0> f()
NameError: undefined local variable or method `x' for main:Object
from (irb):11:in `f'
from (irb):14:in `evaluate'
from org/jruby/RubyKernel.java:1101:in `eval'
from org/jruby/RubyKernel.java:1501:in `loop'
from org/jruby/RubyKernel.java:1264:in `catch'
from org/jruby/RubyKernel.java:1264:in `catch'
from C:/jruby-1.7.12/bin/jirb_swing:53:in `(root)'
public class Test {
public void f() {
boolean isInt = x instanceof Integer;
Integer x = 10;
}
}
>javac Test.java
Test.java:3: error: cannot find symbol
boolean isInt = x instanceof Integer;
^
symbol: variable x
location: class Test
1 error
Oh no, it's now in line with just about every other lexically scoped language.If it can either return "undefined" or throw an exception, can you see why that would be a problem?
typeof x; // throws an error
let x = 1;
This doesn't: typeof x; // returns "undefined"
var x = 1;
While using variables before declaring them is bad practice, I think it's fair to argue that this behaviour is inconsistent.Sure there's a zillion frameworks and patterns for shoehorning OO into JavaScript. But the point is, ES6, is standardising it. That means libraries going forward will assume this is the way it's done and build on top of it. It gives them more expressive power and better inter-op.
Also, default params are long overdue but I'm not sure that makes them "so what". I'd rather avoid mangling the arguments array in some awkward if statements.
Bottom line, there's a lot of things about JS that aren't great, but it's what all the browsers actually run so we're kind of stuck with it and any improvements are welcome.
(Even if you use something like ClojureScript or CoffeeScript, JS is still the target language and the runtime. Improvements and standardisation matter.)
The egregious part is that, by turning something into a language feature, those who don't use it are often forced to take it into account in their code; especially library authors.
If I look at most of the libraries commonly used in production JS, pretty much none of them apply classic OOP principles.
In that case, his opinion on class vs. prototypes is that it misses the point: http://lists.squeakfoundation.org/pipermail/squeak-dev/1998-...
As an aside, prototypes are strictly more powerful than classes, so they're no "shanty": http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/De... (esp. section 6)
There are dozens of ways to do classes/inheritance. Standardizing this means better tooling, documentation, and interoperability.
>Default parameters. By itself, this is another “so what” feature.
It's extremely useful in conjunction with named parameters. Named parameters are so much better than "option" objects.
If it's right in the function's signature, you can see right away how this thing is supposed to be used. Since it's declarative, it can be also picked up by your editor, too.
>let considered harmful
No, it's not. It makes variable declaration work like everywhere else. Function scope is the super weird anomaly.
Did people actually use the side-effect var-hoisting intentionally within their code?
Pretty much any JS style-guide worth its salt suggests manually moving var declarations to the top of scope since it's nice to know ahead-of-time which indicators of state you should be keeping an eye on.
The idea of inspecting a variable that is later-on defined with let seems baffling to me. I can't think of any reason why you would want to do this.
But I don't think the `let` syntax is going to be a problem for people who write plain JavaScript. It's more likely to it might become a problem for languages that compile to JavaScript. (For example, soak operators in CoffeeScript.)
Interesting point, but I disagree. I think that the lack of hoisting is one of the benefits of `let`. It works in a different way, which is more in line with other languages. Sometimes, you don't want a bunch of variables at the top of your function. Many functions do not need to be executed in the way that hoisting makes easier.
By the way, quoting Betteridge’s law of headlines at the beginning of your article whose headline is a question does not mean you get a free pass of using such a headline ;)
What would be the usecase of typeof'ing something undeclared in a block scope and then declaring the let further down?
Even more so with strict mode which does't really allow you to use undeclared variables anyway.
function a(){
setTimeout(b, 1000);
}
function b() {
setTimeout(c, 1000);
}
function c() {
}Hoisting works like this:
a();
function a() {
console.log("FOO");
}
Which might or might not be more readable, depending on your tastes.I find them a whole lot easier to reason about than prototype based inheritance. (But then I have more experience with class based languages).
As to the author's problem? I imagine it might have some deep seated cause related to the above, but that keeps getting translated to abstract disdain for the concept. Which is tragic.
I could easily argue the opposite. Classes reduce complexity, and increase composability. Classes allow you to group methods in a cohesive manner into a single entity. For example, a class named Queue, List, or Vector would imply to the programmer what it does without them reading any code at all.
>With OO you end up with a soup of inheritence and patterns.
Just because programmers don't make clean code, doesn't mean the whole idea is somehow lesser then just using functions. Having a hodge-podge of 2000 line functions in one massive file is just as evil as "dirty" OOP code. At least classes encourage you to group your functions in some hopefully sane manner.
>Functions are way easier to compose and reason about.
Functions are easy to compose and reason about, however, that does not mean that classes and OOP are not as easy. Each have their own clear costs/benefits. OOP, and procedural programming, should both be in a programmers toolbox.f
That said, I find FP easier to reason about and comprehend, but that is just one man's opinion. I also find it more fun.
The "bad bet" I was referring to was that you can make JS impersonate Java. That strikes me as a losing proposition. Sugaring up prototype inheritance to look like class-based inheritance just muddies the water.
The rules of let are that any reference to the variable before the let declaration (the "temporal dead zone"), it's a reference error. So the reference error is being thrown before typeof is invoked.
Currently:
JSONParseStream.prototype = Object.create(Transform.prototype);
function JSONParseStream(options) {
Transform.call(this, options);
...
}
JSONParseStream.prototype = Object.create(Transform.prototype);
Object.defineProperty(JSONParseStream.prototype, 'constructor', {
value: JSONParseStream,
enumerable: false,
writable: true,
configurable: true
}
JSONParseStream.prototype._transform = function(chunk, encoding, cb) {
...
}
With ES6: class JSONParseStream extends Transform {
constructor(options) {
super(options);
...
},
_transform(chunk, encoding, cb) {
...
}
}
That being said, the fact that previously you could not simply use the word class meant that despite efforts of people unused to the language (let me tell you how many half assed class libraries i've seen in code written by people who mainly code in python or java but have some web code as well), unnecessary inheritance tends to be avoided. The lack of a class keyword tends to get javascript writers to avoid inheritance for things best served by mix-ins or object literals, or whatever. I predict that adding the class keyword, while saving me some time will also cause an uptick to unnecessarily convoluted inheritance patterns as new users find they can implement all of their design patterns verbatim without thinking if they really need the ajax method, the json parser, and the url builder to all be in objects that inherit from each other.Do you realize that if the optional arguments were not included in Function#length, you'd just be saying "They are not reflected in the function’s length property. C'mon, man" instead ?
Also, I don't understand Whoop-dee-freakin’-doo.
Whoop-dee-freakin’-doo
http://en.wiktionary.org/wiki/whoop-de-doo
http://en.wikipedia.org/wiki/TmesisAs for Whoop-dee-freakin’-doo, no, it don't think it means anything in the context. That's not an argument, and the following sentence isn't either. Maybe I don't understand because english isn't my native language, tho.
Let's say we have these functions:
function getElem(arr, index=0) { return arr[index]; }
var curried = curry(getElem);
In a hypothetical world where default arguments are included in the length, we would have to supply them explicitly. That's no big deal though, it's just a potential inconvenience: // Hypothetical, "better" semantics
var arr = ["a", "b", "c"];
console.log(curried(arr)); // partially-applied function, *not* "a"
console.log(curried(arr, 0)); // "a"
console.log(curried(arr, 1)); // "b"
The ES6 semantics is worse because we cannot provide a non-default argument to a curried function: // Actual, "worse" semantics
console.log(curried(arr)); // "a"
console.log(curried(arr, 0)); // Error: attempts to run `"a"(0)`, but "a" is not a function
console.log(curried(arr, 1)); // Error: attempts to run `"a"(1)`, but "a" is not a function
The reason this is particularly unfortunate is that one major use-case of currying is to provide default arguments! In other words, by adding default arguments to the language in this way, ES6 is breaking an existing mechanism for default arguments!I would argue that currying is actually more general than default arguments, so if it's a choice between one or the other, they should have added currying to the language instead of default arguments.
They're not quite comparable, but you can think of currying as supplying default arguments "dynamically" (at the call site), whereas regular default arguments are supplied "statically" (at the definition site). For example:
// Give "y" a default value for everyone
var defaultMultiply = function (x, y=2) { return x * y; };
console.log(defaultMultiply(5, 7)); // 35
console.log(defaultMultiply(5)); // 10
// Don't commit to any defaults yet
var curryMultiply = curry(function(x, y) { return x * y; });
console.log(curryMultiply(5, 7)); // 35
// Give "x" a default value, to act like defaultMultiply
var double = curryMultiply(2);
console.log(double(5)); // 10
// Give "x" a different default, which we can't do with defaultMultiply
var triple = curryMultiply(3);
console.log(triple(5)); // 15
I've implemented and used currying in JS, PHP and Python, and I found JS the most pleasant, specifically because it didn't have default values.e.g.
ES5
users.map(function(user) {
return user.name
}).filter(function(name) {
return name.length < 30
}).sort(function(a, b) {
return a.length - b.length
})
vsES6
users
.map(user => user.name)
.filter(name => name.length < 30)
.sort((a, b) => a.length - b.length)
Contrived, but typical example. var _this = this;
call(function (){
return _this.value;
});
versus call(() => this.value);
So yeah, much more readable, and less issues with this binding to some other caller or window. function(){}.bind(this)
vs
() => {}
And for a single expression the `{}` are optional and a `return` is implied, which is pretty nice for .map()/.sort(), etc.Automatically bound `this` is super important. It's very easy to forget one `.bind(this)` (or `that` alias) somewhere, especially when you have several levels of callback nesting.
Without fat arrow: function outer() { function inner() { this === inner.this; } }
With fat arrow: function outer() { var inner = => this === outer.this; }
Fat arrow syntax is much more terse than a function declaration and also handles the case of passing the parent's execution scope.
When are proper tail calls expected to show up? Looks pretty bleak.
[1] http://en.wikipedia.org/wiki/Betteridge%27s_law_of_headlines