Reputation: 214949
I often see something like this in other people's scripts:
bar = Array.prototype.slice.call(whatever, 1)
However, the following shorter notation works fine as well:
bar = [].slice.call(whatever, 1)
Are these two constructs fully equivalent? Are there engines (browsers) that treat them differently?
Upvotes: 5
Views: 58
Reputation: 27460
They are not equivalent strictly speaking. This construction:
[].slice.call(whatever, 1)
allocates new instance of array on the heap just for the purpose of getting property from it. So it has side effect - leaves garbage in the heap.
Upvotes: 1
Reputation: 235992
Yes, fully equivalent.
It happens to be that the access via .prototype
is slightly faster because no new object instance needs to get created. However, thats what we call microoptimization.
A nice way to get entirely rid of deep chaining, is to invoke Function.prototype.bind
.
Example
(function( slice ) {
slice( whatever, 1 );
}( Function.prototype.call.bind( Array.prototype.slice )));
Upvotes: 5