Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the JavaScript equivalent of Ruby's splat operator?

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?

like image 801
Ajedi32 Avatar asked Dec 29 '13 04:12

Ajedi32


People also ask

What is Ruby splat operator?

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.

What is Kwargs in JavaScript?

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.

Does Ruby have a spread operator?

In both Ruby and JavaScript, you can use splat/spread to build up a new array from existing arrays.


1 Answers

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

like image 50
Ajedi32 Avatar answered Oct 07 '22 22:10

Ajedi32