Read more

JavaScript: Calling a function with a variable number of arguments

Henning Koch
June 29, 2014Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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

# 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".

EcmaScript 6 (ES6)

console.log(...array)

This is supported by all current browsers, but not IE 11. If you need to support IE11 you need a transpiler Show archive.org snapshot .

EcmaScript 5 (ES5)

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

CoffeeScript

console.log(array...)
Posted by Henning Koch to makandra dev (2014-06-29 21:06)