4 ms·
While I really like comprehensions, as soon as you need a conditional, or any level of nesting, you pretty much have to break it out into a loop to keep it read
by zaius 11y ago
While I really like comprehensions, as soon as you need a conditional, or any level of nesting, you pretty much have to break it out into a loop to keep it readable.
OTOH, block syntax (I don't think that's the correct term for it) has always irked me in JS, due to verbose function declaration, and no implicit return. So beautiful syntax in ruby like:
some_array.map { |el| el.length }
# Or the succinct version:
some_array.map(&:length)
Looks like this in JS:
someArray.map(function() { return this.length; });
Now that ES6 has arrow functions with implicit returns, we can do this:
someArray.map( s => s.length );
Since both comprehensions and implicit return functions are being released around the same time, I'll be interested to see which of the two gets more adoption.
- oldmanjay 11y agoYou call it beautiful, but that's a fair stretch. It's more compact than JavaScript but to non-Ruby eyes, there's no real beauty to be found. It's just simple substitutions that otherwise look the same.
- deleted 11y ago[deleted]
- lobster_johnson 11y agoA key difference in Ruby is that while blocks are conceptually just another argument, they aren't part of the syntactical argument list. This: strings.map { |s| s.upcase } is actually: strings.map() { |s| s.upcase } ...and this is what it's not: strings.map({ |s| s.upcase }) # Invalid It's subtle, but it does make for a simpler, more readable syntax that lends itself to DSLs, since no parantheses are needed: validate :name { |name| errors.add("Bad name") unless name } It's feasible in other languages, of course; Elixir, for example, introduces a Ruby-like "do" block syntax which is more regular than Ruby's. It might be too late for JavaScript, but I'm no parser expert.
- zaius 11y agoThey're simple examples that fit into one line. The difference is more notable on longer chains. I think people currently avoid this block style[1] syntax in JS because it's verbose. Arrow functions fix that. [1] Again, not sure of the correct term for this - functional style?