In Ruby, you can use the splat (*
) operator to capture a variable number of arguments to a function, or to send the contents of an array to a function as an argument, like so:
def example(arg1, *more_args)
puts "Argument 1: #{arg1.inspect}"
puts "Other arguments: #{more_args.inspect}"
end
test_args = [1, 2, 3]
example(*test_args)
Output:
Argument 1: 1
Other arguments: [2, 3]
What's the equivalent of this in JavaScript?
Splat operator or start (*) arguments in Ruby define they way they are received to a variable. Single splat operator can be used to receive arguments as an array to a variable or destructure an array into arguments. Double splat operator can be used to destructure a hash.
kwargs(function, object, …) Call a given function with a kwarg object. Any extra named params will be added to the argument list in the order they are read, followed by any extra arguments. function letters(a, b, c) { return '' + a + b + c.
In both Ruby and JavaScript, you can use splat/spread to build up a new array from existing arrays.
In older versions of JavaScript (ECMAScript 5), no exact equivalent to this exists. In modern browsers which support ECMAscript 6 though, there is something very similar denoted by three periods (...
).
When used in function calls and array declarations this triple-dot syntax is known as the spread operator. When used in a function definition, it is called rest parameters.
Example:
function example(arg1, ...more_args) { // Rest parameters
console.log("Argument 1: ", arg1)
console.log("Other arguments: ", more_args)
}
test_args = [1, 2, 3]
example(...test_args) // Spread operator
Output:
Argument 1: 1
Other arguments: [2, 3]
The spread operator and rest parameters are available in the latest versions of all major browsers (except Internet Explorer) and the latest Node.js LTS release.
Full compatibility tables: Spread operator, Rest parameters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With