I’m doing my first internship and it's going good and I'm trying to keep up with everything the other programmers talk about. A senior programmer told me the other day that Ruby’s ability to pass code blocks directly into functions was much more preferable than using anonymous functions in JavaScript. It’s my understanding that JS anonymous functions are precisely the same thing – simply passing a code block via a variable as a parameter. Are there real-world examples of code block parameters being superior to anonymous functions? Or is it simply a matter of preference in one language over the other, a code readability/re-usability issue, or am I simply misunderstanding some other fundamental concept? This was a passing conversation about the relative merits of which language to use for some task, and not a concrete work problem, which is maybe why I’m confused. I Googled a couple naive examples of code blocks and had little trouble implementing them in JS. Looking forward to any input on the matter (anonymous or otherwise).
1 Answer
They are not exactly the same. The main reason is the use of implicit and explicit return values.
You can read a good article here: http://yehudakatz.com/2012/01/10/javascript-needs-blocks/
5 Comments
ialexander
This is a truly fantastic read! "This impression, which I admittedly shared in my early days as a Ruby/JavaScript developer, misses an important subtlety that turns out to have large implications. This subtlety is often referred to as “Tennent’s Correspondence Principle”. In short, Tennent’s Correspondence Principle says: “For a given expression expr, lambda expr should be equivalent.” " Thanks for that!
ialexander
It was in fact the exact answer. Accepted. I was busy reading the blog ;>
Darek Nędza
@wormtown You don't need anything more?
ialexander
@DarekNędza No, thank you. phoet hit upon to exact answer I was looking for. The exact difference between the two.
RJM
Am I correct in my understanding that with the latest versions of ecma that this is no longer true?
def meth1; yield if block_given?; end; meth1 { puts 42 }?