Slice

slice is a useful little function.

For these examples, I'm going to use lodash's _.range function to generate arrays. For example, _.range(1, 11) returns the array:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Check this out:

_.range(1, 11).slice(5)  
_.range(1, 11).slice(0, 5)  

These return

[ 6, 7, 8, 9, 10 ]

and

[ 1, 2, 3, 4, 5 ]

respectively.

slice is an array method that returns some sub-part of the array. Its first argument is the start of the sub-part, and its second argument is just after the end of the sub-part.

slice has default arguments; the default of the first is 0 and the default of the second is the array's length.

So

_.range(1, 11).slice()  

returns

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Here's an interesting thing, in the body of every function there is an arguments object:

function log_args() {  
    console.log(arguments)
}

log_args('these', 'are', 'arguments')  

The above code prints out:

{ '0': 'these', '1': 'are', '2': 'arguments' }

Inconveniently, arguments is not an array, but we can make it so!

function caps() {  
    return Array
        .prototype
        .slice
        .call(arguments)
        .map((string) => string.toUpperCase())
}

console.log(caps('these', 'are', 'arguments'))  

The above code prints out:

[ 'THESE', 'ARE', 'ARGUMENTS' ]

The ability to turn a function's arguments into an array (using Array.prototype.slice.call can be pretty useful. More on that later... :)

Looking for a software developer?