Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

Array.prototype.splice - help to understand a lesson

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?

Upvotes: 9

Views: 576

Answers (3)

Grzegorz Adam Kowalski
Grzegorz Adam Kowalski

Reputation: 5565

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.

Upvotes: 2

Cichelero
Cichelero

Reputation: 331

You are right, calling the Array.prototype.splice with [1] is probably a mistake.

According to MDN docs for splice, this method's first argument is supposed to be a number. Chrome will indeed interpret [1] as 1 and skip the first argument.

You should check if the first argument is supposed to be skipped, otherwise better make your for loop directly over the function arguments.

Upvotes: 1

Mike Jerred
Mike Jerred

Reputation: 10525

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),

Upvotes: 6

Related Questions