Diving Into Lodash: Slice Method

Updated: 21st March

I have been using underscore for long time now, and have recently upgraded to using Lodash.

Lets dive into the Slice method of Lodash.

/**
 * Slices the `collection` from the `start` index up to, but not including,
 * the `end` index.
 *
 * Note: This function is used, instead of `Array#slice`, to support node lists
 * in IE < 9 and to ensure dense arrays are returned.
 *
 * @private
 * @param {Array|Object|String} collection The collection to slice.
 * @param {Number} start The start index.
 * @param {Number} end The end index.
 * @returns {Array} Returns the new array.
 */
function slice(array, start, end) {
  start || (start = 0);
  if (typeof end == 'undefined') {
    end = array ? array.length : 0;
  }
  var index = -1,
      length = end - start || 0,
      result = Array(length < 0 ? 0 : length);

  while (++index < length) {
    result[index] = array[start + index];
  }
  return result;
}

and now line by line:

  1. start || (start = 0)

    I have been doing undefined check using start = (typeof start === 'undefined' ? 0 : start) but snippet in Lodash is short and efficient.

  2. if (typeof end == 'undefined') {

    This should have been a trinary === check. #fail #nothingtolearn The typeof function always return string and hence we don't need strict equality check. Corrected by John

  3. result = Array(length < 0 ? 0 : length)

    Pre-initialization of array with specified length avoids unwanted undefined values in array. Initializing arrays with length optimizes setting values of array. (Thanks John for correction);

  4. while (++index < length) {

    Better alternative to traditional for loop that I have been using for iterating over the array using index.

Together, lets dissect more methods in Lodash to learn efficient Javascript techniques

This entry was published on 20th Mar, 2013.