JavaScript Quick Tips #3

Function Parameters from Array Values

Suppose we have a function with parameters and an array:

A Function and an Array
1
2
3
4
5
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
1
2
3
4
5
6
7
8
9
10
//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 to an array:

Common Push Operation for Arrays
1
2
var friendlyNeighborhoodArray = [];
friendlyNeighborhoodArray.push('Mr. Rogers');

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

Use Array Length to Add Items to Array
1
2
3
4
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.