Let's break down your code step by step.
[1,4,5,6,7,2,3]
This is an array literal. That is, to write [1,4,5,6,7,2,3]
is a bit like saying new Array(1,4,5,6,7,2,3)
. Simply put, the array literal evaluates to a new array with the described contents.
[1,4,5,6,7,2,3]["sort"]
Now this bit is interesting, because knowing []
creates array literals makes us think ["sort"]
is also an array literal. Not quite - this is an example of Javascript bracket notation, where we access the properties of a preceding object with the syntax someObject["propertyName"]
, equivalent to someObject.propertyName
. Check out this SO answer for more info on bracket notation.
So we know the sort
property of Array
s, Array.sort
, is a function. To write [1,4,5,6,7,2,3]["sort"]
is like saying ([1,4,5,6,7,2,3]).sort
. To invoke a function, we use parentheses with the arguments we want:
[1,4,5,6,7,2,3]["sort"]();
This is like saying ([1,4,5,6,7,2,3]).sort();
.
Now in your code, you've passed in a 0
as the argument for Array.sort
. However, this 0
actually has no effect on the result of sorting! That's because the sort
method for arrays takes an optional comparison function. As 0
is not a function, Array.sort
will simply ignore it. In fact, in the Firefox console, running [1,4,5,6,7,2,3]["sort"](0);
gives us a TypeError: invalid Array.prototype.sort argument
.
Putting it all together, we can reverse our result with the following:
[1,4,5,6,7,2,3]["sort"]()["reverse"]();
Equivalent to:
([1,4,5,6,7,2,3]).sort().reverse();