14

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?

Ajedi32
  • 45,670
  • 22
  • 127
  • 172
  • possible duplicate of [Splat operators in JavaScript, equivalent to \*args and \*\*kwargs in Python?](http://stackoverflow.com/questions/17380315/splat-operators-in-javascript-equivalent-to-args-and-kwargs-in-python): Python splats are analogous on definition and call. – Ciro Santilli OurBigBook.com Oct 22 '14 at 07:08

2 Answers2

21

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

Ajedi32
  • 45,670
  • 22
  • 127
  • 172
  • ES6's "spread" operator is ruby splat's "split" operation, and ES6's "rest" parameter is like ruby splat's "slurp/collect" operation. See: http://tony.pitluga.com/2011/08/08/destructuring-with-ruby.html – Magne Feb 28 '18 at 11:48
5

The first use can be accomplished (messily) using Array.slice(arguments).

The second can be accomplished by using the .apply() method of your function.

curiousdannii
  • 1,658
  • 1
  • 25
  • 40