Search code examples
javascriptrubyecmascript-5ecmascript-harmony

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?


Solution

  • 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