I found this piece of code on StackOverflow:
[].sort.call(data, function (a, b) {})
Is []
a shorthand for "sort data values and then make an array with the same name"?
[]
is just array literal. It's an empty array, because it doesn't contain any elements. In this context it's a shortcut to Array.prototype
.
This code basically allows you to use Array.prototype.sort()
method even on values which are not arrays, for example arguments
.
Further explanation:
[] // Array literal. Creates an empty array.
.sort // Array.prototype.sort function.
.call( // Function.prototype.call function
data, // Context (this) passed to sort function
function (a, b) {} // Sorting function
)
Assuming that you have an array-like object, like this:
var obj = {0: "b", 1: "c", 2: "a", length: 3};
It's array-like, because it has numeric keys and length
property. However, you can't just call .sort()
method on it, because Object.prototype
doesn't have such method. You can instead call Array.prototype.sort()
in context of your object. That's exactly what Function.prototype.call()
method is for. The first argument of .call()
method is context passed to the function, and the rest are arguments passed to the function. For example:
Array.prototype.sort.call(obj)
returns sorted object, because Array.prototype.sort
behaves like it was obj
method.
Note that using Array.prototype
is generally better practice than using array literal, because it's more explicit.
See also:
Function.prototype.call()
docsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With