74

I'm currently reading through this jquery masking plugin to try and understand how it works, and in numerous places the author calls the slice() function passing no arguments to it. For instance here the _buffer variable is slice()d, and _buffer.slice() and _buffer seem to hold the same values.

Is there any reason for doing this, or is the author just making the code more complicated than it should be?

 //functionality fn
 function unmaskedvalue($input, skipDatepickerCheck) {
     var input = $input[0];
     if (tests && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) {
         var buffer = _buffer.slice();
         checkVal(input, buffer);
         return $.map(buffer, function(element, index) {
             return isMask(index) && element != getBufferElement(_buffer.slice(), index) ? element : null; }).join('');
    }
    else {
        return input._valueGet();
    }
}
2
  • 2
    No competent programmer would ever make code more complicated than it needs to be. Commented Jul 2, 2012 at 1:32
  • 5
    It is necessary. The slice method is being used at the beginning of the function to backup the original array items before being modified by the function, this way the author has access to the positions, keys and values of the original array even after and while editing the array. This is indispensable when making a responsible string manipulating interface, as your example plugin. Complementing on @alex's comment, if it's there, there's a reason for it. Ctrl+F the source and look for where it's being accessed later on if you need a better understanding. Commented Jul 2, 2012 at 1:39

2 Answers 2

115

The .slice() method makes a (shallow) copy of an array, and takes parameters to indicate which subset of the source array to copy. Calling it with no arguments just copies the entire array. That is:

_buffer.slice();
// is equivalent to
_buffer.slice(0);
// also equivalent to
_buffer.slice(0, _buffer.length);

EDIT: Isn't the start index mandatory? Yes. And no. Sort of. JavaScript references (like MDN) usually say that .slice() requires at least one argument, the start index. Calling .slice() with no arguments is like saying .slice(undefined). In the ECMAScript Language Spec, step 5 in the .slice() algorithm says "Let relativeStart be ToInteger(start)". If you look at the algorithm for the abstract operation ToInteger(), which in turn uses ToNumber(), you'll see that it ends up converting undefined to 0.

Still, in my own code I would always say .slice(0), not .slice() - to me it seems neater.

Sign up to request clarification or add additional context in comments.

6 Comments

This is really confusing given that the array.slice() claims to require at least one argument
@meawoppl - I've updated my answer to explain why it works with no arguments.
Thanks for the no arguments explanation, was looking for that
"I'm going to slice this sandwich not at all"
it makes a shallow copy which I just read means that the copied object is not just copying the entire array, it seems that it copies the array but leaves all the old memory references in place - so you change a string value on the copied array and it will be two different arrays with different values since a string is stored directly as a value, but you change a property on an object and it updates both. I think what you wanted here is a deep copy.
|
1

array.slice() = array shallow copy and is a shorter form of array.slice()

Is there any reason for doing this, or is the author just making the code more complicated than it should be?

Yes there may be a reason in the following cases (for which we do not have a clue, on whether they apply, in the provided code):

  • checkVal() or getBufferElement() modify the content of the arrays passed to them (as second and first argument respectively). In this case the code author wants to prevent the global variable _buffer's content from being modified when calling unmaskedvalue().
  • The function passed to $.map runs asynchronously. In this case the code author wants to make sure that the passed callback will access the array content as it was during unmaskedvalue() execution (e.g. Another event handler could modify _buffer content after unmaskedvalue() execution and before $.map's callback execution).

If none of the above is the case then, yes, the code would equally work without using .slice(). In this case maybe the code author wants to play safe and avoid bugs from future code changes that would result in unforeseen _buffer content modifications.

Note:

When saying: "prevent the global variable _buffer's content from being modified" it means to achieve the following:

  • _buffer[0].someProp = "new value" would reflect in the copied array.
  • _buffer[0] = "new value" would not reflect in the copied array.

(For preventing changes also in the first bullet above, array deep clone can be used, but this is out of the discussed context)

Note 2:

In ES6

var buffer = _buffer.slice();

can also be written as

var buffer = [..._buffer];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.