Arrow Function Comparison

Introduction

Arrow Function looks like lambda and procs in Ruby. Are they similar?

Yes, JavaScript arrow functions have some similarities with Ruby’s lambdas and procs, as they are all anonymous functions that can be stored in variables, passed as arguments to other functions, and created dynamically. However, there are also some differences due to the different nature of the languages and how they handle scope and this.

Here’s a simple comparison:

JavaScript Arrow Functions

JavaScript arrow functions are anonymous functions that you can assign to a variable or pass as a function argument. They have a simplified syntax compared to regular functions, and they handle this differently (they do not have their own this context, instead, they inherit this from the surrounding code).

Example:

1
2
3
let greet = () => console.log("Hello, World!");

greet(); // Outputs: "Hello, World!"

Ruby Lambdas

Ruby lambdas are objects that encapsulate a block of code, which can be stored in a variable or passed around to methods. They are very similar to procs, with a couple of differences (lambdas check the number of arguments, while procs do not, and return inside lambdas exits the lambda, while return inside a proc exits the method containing the proc).

Example:

1
2
greet = lambda { puts "Hello, World!" }
greet.call # Outputs: "Hello, World!"

Ruby Procs

Procs in Ruby are very similar to lambdas. They are also objects that contain a block of code, which can be stored in a variable or passed as a method argument. The differences between procs and lambdas were mentioned above.

Example:

1
2
greet = Proc.new { puts "Hello, World!" }
greet.call # Outputs: "Hello, World!"

In conclusion, while there are similarities between JavaScript arrow functions and Ruby’s lambdas/procs (like being able to store functions in variables and pass them as arguments), there are also important differences due to the languages’ different handling of scope and context.