Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [ ] stand for? [duplicate]

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

like image 996
Janusz Bieraszewski Avatar asked Dec 10 '22 18:12

Janusz Bieraszewski


1 Answers

[] 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() docs
  • How does the "this" keyword work?
  • Array.prototype.sort.apply( someArray, args ) vs someArray.sort.apply( someArray, args )
  • How to sort javascript object array by element.name
  • What is array literal notation in javascript and when should you use it?
like image 194
Michał Perłakowski Avatar answered Dec 29 '22 14:12

Michał Perłakowski