Posted over 4 years ago. Visible to the public. Repeats.

Javascript: Calling a function with a variable number of arguments

This card describes how to pass an array with multiple element to a JavaScript function, so that the first array element becomes the first function argument, the second element becomes the second argument, etc.

Note how this is different from passing the entire array as the first argument. Compare these two different ways of calling fun() in Ruby:

Copy
# Ruby array = [1, 2, 3] fun(array) # same as fun([1, 2, 3]) (1 argument) fun(*array) # same as fun(1, 2, 3) (3 arguments)

Depending on your culture the spreading of array elements into multiple argument slots is called "splat args" or "varargs" or "spread args" or "rest operator".

Plain JavaScript

Copy
var array = [1, 2, 3]; console.log.apply(console, array);

CoffeeScript

Copy
console.log(array...)

EcmaScript 6 (ES6)

Copy
console.log(...array)

This is supported by current browsers and Microsoft Edge, but not IE 11. If you need to support IE11 you need a transpiler.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Henning Koch
Last edit:
6 months ago
by Dominik Schöler
Keywords:
varargs, splat, rest, arguments
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more