Javascript’s astonishing sort function 😲

Topher Winward
7 min readJun 14, 2018

When we write code, we should take a moment to consider, “If someone else was reading this for the first time, what would they expect?”

Take the following piece of code — please take a moment to really consider, what you expect the output to be before you run it. I ask this, even if you are not a JavaScript developer.

Despite being a seemingly simple piece of code — only 4 lines, 3 function calls, and only one “weird” bit of syntax on line 4, there is a large amount going on in this snippet.

I asked a few colleagues, from junior to senior levels, with varying experience in either JavaScript or C++ (from 1 year to 10+), and all were tripped up in a different way by this snippet.

🔍 Before running, let’s examine our assumptions

What are some of the possible points of confusion that they encountered here? These are thoughts my colleagues mentioned and expected before running the code — not what the actual behaviour is.

  • “You used const to declare A, yet you clearly mutate it on line 4.”
  • .push makes a copy of the array and adds the value to the end.”
  • .push makes a copy of…

--

--

Topher Winward

Joy finder and software developer. I design and develop software that helps people be as effective as they can be.