4

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"?

Michał Perłakowski
  • 70,955
  • 24
  • 137
  • 155
  • 2
    probably need some more context for this line of code. As it stands right now it's not even valid javascript. – Brian Driscoll Jan 25 '16 at 18:27
  • 4
    That simply initializes an empty array `[]`. It's also known as an array literal. See this: [stackoverflow.com/questions/1094723/](http://stackoverflow.com/questions/1094723/what-is-array-literal-notation-in-javascript-and-when-should-you-use-it) for more details... – War10ck Jan 25 '16 at 18:27
  • 1
    [] is an array and it is used here to call the sort on data that is not an array: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/call – mplungjan Jan 25 '16 at 18:28

1 Answers1

13

[] 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:

Community
  • 1
  • 1
Michał Perłakowski
  • 70,955
  • 24
  • 137
  • 155