Description
In Javascript, for (x in y)
and if(x in y)
mean, respectively, "do this for every property of y
," and "do this if y
has a property named x
".
In Coffeescript, for x in y
and if x in y
mean, respectively, "do this for every array element of y
," and "do this if y
has a property named x
."
That is, in Coffeescript, the keyword in
can refer to both array items and property names, depending on the context. This is somewhat inconsistent. Since Coffeescript already changes the meaning of the in
operator in an iteration context, and introduces the of
keyword for object-property iterations, it would make sense if we also used if x of y
to mean "do this if y
has an object-property named x
."
The meaning of in
has already been altered from its Javascript origins, so it would be consistent if its meaning as an infix operator matched its iteration meaning. Conversely, the current use of the of
keyword could be expanded to take its place as a test of object-properties.
If we make this change, then if x in y
could take on the meaning "do this if x is an array-element of y." This could potentially be compiled as follows:
# Coffeescript:
if x in y
do_something()
// Javascript:
if ((function(){
for (var i = 0; i < y.length; ++i) {
if (y[i] === x) return true;
}
})()) {
do_something();
}
# Coffeescript with array literal optimization:
if x in ['a', 'b', 'c']
do_something()
// Javascript:
var _a;
if ((_a = x) === 'a' || _a === 'b' || _a === 'c') {
do_something();
}