JavaScript Quick Tips #3

06/19/2013, Wed
Categories: #JavaScript
Tags: #jQuery

Function Parameters from Array Values

Suppose we have a function with parameters and an array:

// A Function and an Array

function doSomething(stuff, thing1, thing2) {
  console.log("params were concatenated:" + " " + stuff + thing1 + thing2);
}

var justAnArray = ["a", "b", "c"];

We want to pass the function parameters the values from the array. So 'a', 'b', 'c' will correspond to stuff, thing1, and thing2.

Instead of iterating through the array to get the items into the function or doing manual array index reference, you can use JavaScript's apply function.

// Example of Using Apply

// the pattern for using apply
// theFunction belongs to theContext
// theFunction.apply(theContext, theArray);

// in our example, theContext is undefined
// because theContext refers to an object
// but we do not have one

// logs out 'params were concatenated: abc'
doSomething.apply(undefined, justAnArray);

Alternative to Using Push for Arrays

The usual way of adding an item to an array is to use push something into an array:

// Common Push Operation for Arrays

var friendlyNeighborhoodArray = [];
friendlyNeighborhoodArray.push("Mr. Rogers");

Another way to perform a push is to get the length of array and use that value as the index to set a value:

// Use Array Length to Add Items to Array

var friendlyNeighborhoodArray = [],
  arrayLength = friendlyNeighborhoodArray.length;

friendlyNeighborhoodArray[arrayLength] = "Mr. Rogers";

This way is a not as clean as using push, but it looks to perform better than the native push.