Passing an array to a function

ES6 has brought a lot of efficiencies to JS. One such new tool is the spread operator, the dot-dot-dot, or three dots ... syntax.

This operator results in, I'd argue, cleaner code that's easier to read and follow as well as adding some nice abilities.

The Old Way

You have an array and you want to use the elements individually within a function:

function doSubroutine (x, y, z){
    var a = x + y;
    var b = a*z;
    return b;
}
var arr = [1,2,3];

// call function, passing arr
doSubroutine.apply(null, arr); // outputs 9

The null parameter of the .apply() method lets you set the context of this, which in this doSubroutine() function is not needed.

As an aside, there are two other methods for the JS function: .call() which you pass regular (non-array) arguments to the function, and .bind() which creates/returns a new function.

The ES6 Way

The Spread Operator ... allows you to pass an array to a function without using the .apply() method. This new way is much cleaner: doSubroutine(...arr).

Notice that there is no need to pass to the function, the null parameter. You still can, and you'll get the same result, but now you only need to pass in the array arr as the argument.

function doSubroutine (x, y, z){
  let a = x + y;
  let b = a*z;
  return b;    
}
const arr = [1,2,3];

// call function passing args
doSubroutine(...arr); // outputs 9

This just touches the surface (as it should be in a 2 Minute Tip 😃).

Fire up your browser console and follow along:

  • What happens when const arr = [1,2,3,4];?
    Only the first three elements of the array are used.

  • What happens if const arr = [1,2];?
    Our lovely NaN.

  • So, let's add another number to the array: doSubroutine(...arr, 3); You can think of this as push()-ing the '3' onto the end of the array. Now doSubroutine() works fine.

  • What happens if const arr = [1,2,3,4];?
    The function just ignores any of the trailing/extra elements of the array.

So, as is true in any language, and in JS specifically, you need to know the ins-and-outs. Come back for the next installment of 2 Minute Tool Tip: JS Spread Operator -- Combining and Copying Arrays