73

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();
    }
}
Ben
  • 54,723
  • 49
  • 178
  • 224
user886596
  • 2,380
  • 5
  • 31
  • 53
  • 2
    No competent programmer would ever make code more complicated than it needs to be. – alex Jul 02 '12 at 01: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. – Fabrício Matté Jul 02 '12 at 01:39

2 Answers2

113

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.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • 2
    This is really confusing given that the array.slice() [claims to require at least one argument](http://www.w3schools.com/jsref/jsref_slice_array.asp) – meawoppl Jan 28 '13 at 03:48
  • 6
    @meawoppl - I've updated my answer to explain why it works with no arguments. – nnnnnn Jan 28 '13 at 05:50
  • 3
    Thanks for the no arguments explanation, was looking for that – Revolutionair Apr 24 '13 at 10:59
  • 13
    "I'm going to slice this sandwich not at all" – Graham P Heath Jan 23 '16 at 03:00
  • 2
    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. – Craig Oct 29 '18 at 21:32
  • @Craig - It might help to think that an array of objects doesn't actually contain the objects themselves, it contains references to them. A shallow copy copies those references, so yes, the new array ends up containing references to the same underlying objects as the original array. Often that is exactly the result that you would want. The same thing happens just with normal variable assignments with no arrays involved, like `a = {}; b = a;` - now `a` and `b` both refer to the same object so if you say `a.x = 1` then `b.x` will return `1`. – nnnnnn Nov 18 '18 at 00:59
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];

Marinos An
  • 9,481
  • 6
  • 63
  • 96