JavaScript Array.sort() — What is the Output?
This is a daily Javascript challenge from the CodeShot archive. Practice your knowledge of Sort Objects By Property Ascending and improve your technical interview readiness.
const users = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 }
]
const sorted = users.sort((a, b) => a.age - b.age)
console.log(sorted[0].name)
Detailed Explanation
Why This Question Matters
If you've spent any time with JavaScript, you've probably used .sort(). It seems straightforward until you realize it's one of the most deceptive methods in the Array prototype.
The confusion usually stems from two things: how the comparison function actually works and the fact that .sort() mutates the original array. Many developers assume it returns a new, sorted copy (like .map() or .filter()), but that's not the case. If you aren't careful, you'll end up changing your data in places you didn't intend to, leading to bugs that are a nightmare to track down in a large state-driven application.
Understanding the Code
Let's look at the snippet:
Here, we have an array of objects. To sort them by age, we pass a comparison function to .sort().
Inside that function, a and b represent two elements being compared. The logic a.age - b.age is a common shorthand. Here is what's happening under the hood:
- If the result is negative, a is sorted before b.
- If the result is positive, b is sorted before a.
- If the result is zero, the order stays the same.
Since we are subtracting the age of b from a, we are essentially telling JavaScript: "If a is younger than b, put a first." This results in an ascending order (youngest to oldest).
Finding the Correct Answer
If we trace the execution:
1. Bob (25) is the youngest.
2. Alice (30) is next.
3. Charlie (35) is the oldest.
After the sort runs, the users array (and the sorted variable, which points to the same array) looks like this:
[{ name: "Bob", age: 25 }, { name: "Alice", age: 30 }, { name: "Charlie", age: 35 }]
The code then asks for sorted[0].name. The element at index 0 is Bob. Therefore, the output is Bob.
If the comparison had been b.age - a.age, we would have sorted in descending order, and the output would have been Charlie.
Common Mistakes Developers Make
The biggest trap here is the mutation.
In the example above, const sorted = users.sort(...) looks like it's creating a new array. It isn't. .sort() sorts the array *in place*. This means users and sorted are now the exact same array.
In a React or Redux environment, this is a huge red flag. If you mutate state directly, your components might not re-render because the reference to the array hasn't changed, even though the contents have.
Another common mistake is trying to sort numbers without a comparison function. If you do [10, 2, 1].sort(), JavaScript converts the numbers to strings. You'll end up with [1, 10, 2] because "10" comes before "2" alphabetically. Always provide the compare function when dealing with numbers.
Real-World Usage
In a production app, you'll rarely just sort a simple list of three people. You'll be dealing with API responses—maybe a list of products by price or a list of users by "last active" timestamp.
Because mutation is dangerous, the professional way to handle this is to spread the array first to create a shallow copy:
By doing [...users], you create a new array reference. You can sort it as much as you want without messing up the original data source. This is standard practice in modern frontend development to ensure data immutability.
You'll also see this logic used in table headers. When a user clicks "Sort by Price," you're essentially toggling between a.price - b.price and b.price - a.price based on whether the sort direction is ascending or descending.
Key Takeaways
- .sort() mutates the original array. It does not return a new one.
- The comparison function determines the order: negative for ascending, positive for descending.
- Numbers need a compare function. Without it, JS sorts them as strings, which leads to weird results like 10 coming before 2.
- Clone before sorting. Use the spread operator [...] if you need to keep your original data intact.
Why this matters
Understanding Sort Objects By Property Ascending is crucial for passing technical interviews. In real-world applications, this concept often leads to subtle bugs if not handled correctly. For more details, you can always refer to the official MDN Documentation.