Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.prototype.splice - help to understand a lesson

Tags:

javascript

Here is a function from a tutorial:

function add() {
    var values = Array.prototype.splice.call(arguments, [1]),
        total = 0;

    for(var value of values) {
        total += value;
    }

    return total;
}

SOURCE

And the expression Array.prototype.splice.call(arguments, [1]) confuses me.

  1. Why 1?
  2. And why with brackets [1]?

If we pass 1, it represents start position in splice(), so it will skip the first argument we pass to add(), hence it won't add all arguments...

Is this a mistake in the tutorial?

like image 721
Julius Dzidzevičius Avatar asked Apr 30 '18 07:04

Julius Dzidzevičius


2 Answers

Yes this example is mistaken, if you try the code it doesn't work (it ignores the first parameter) exactly as you said. The code would make sense if that line was:

var values = Array.prototype.slice.call(arguments),

Or

var values = Array.prototype.splice.call(arguments, 0),
like image 84
Mike Jerred Avatar answered Sep 28 '22 23:09

Mike Jerred


My guess: the example was made by simplyfing code of another function which had one special parameter and used apply instead of call in ES5 syntax.

In the further part of the tutorial, calculating functions are discussed, whose first argument determines the type of calculations to be performed. If you write them in the ES5 syntax, you'd have to delete the first argument. That explains Why 1 - to delete the first argument. Now, why brackets: there are two nearly identical functions in JS: call and apply. See this note about apply:

While the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.

I think the author of calculation function mistakenly used the syntax for apply and hence the brackets.

like image 33
Grzegorz Adam Kowalski Avatar answered Sep 28 '22 23:09

Grzegorz Adam Kowalski