Understanding Array.prototype.sort() in JavaScript: A Beginner's Guide
Published: 2023-08-25 09:34:57

---
title: Understanding Array.prototype.sort() in JavaScript: A Beginner's Guide
published: true
description: 
tags: 
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zascl6xk1q5rkrkr8c8l.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-08-21 14:43 +0000
---

### **Introduction**

Have you ever stumbled upon the `Array.prototype.sort()` method and found yourself scratching your head? 

![scratching head](https://media.giphy.com/media/cImzxhhaCXabOJ6WaS/giphy.gif)

You're not alone! It's an incredibly useful tool, but it can be somewhat confusing. So, grab a coffee, and let's see how `sort()` operates, using some practical examples to clarify things.

### **Basic Sorting: An Unexpected Twist**

Starting with the fundamentals, the `sort()` method, by default, arranges array elements as strings in ascending sequence:

```javascript
const nums = [40, 1, 5, 200];
nums.sort();
console.log(nums); // Output: [1, 200, 40, 5]
```

Surprised? It's because `sort()` converts numbers into strings for comparison, making '200' smaller than '40'.

### **Tailored Sorting with a Compare Function**

Need more precision? You can employ a `compare` function with `sort()`:

```javascript
nums.sort((a, b) => a - b);
console.log(nums); // Output: [1, 5, 40, 200]
```

Here's the secret formula:
- **Below 0**: `a` comes before `b`.
- **0**: `a` and `b` remain unchanged.
- **Above 0**: `b` comes before `a`.

Want the reverse order? Simply reverse the equation:

```javascript
nums.sort((a, b) => b - a);
console.log(nums); // Output: [200, 40, 5, 1]
```

### **String Sorting**

Need to sort strings? Think about case insensitivity:

```javascript
const fruits = [ 'Kiwi', 'Banana', 'banana', 'Cherry', 'apple', ];
fruits.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(fruits); // Output: [ 'apple', 'banana', 'Banana', 'Cherry', 'Kiwi' ]
```

But why does this also work?

```javascript
const fruits = [ 'Kiwi', 'Banana', 'banana', 'Cherry', 'apple', ];
fruits.sort((a, b) => a.localeCompare(b));
console.log(fruits); // Output: [ 'apple', 'banana', 'Banana', 'Cherry', 'Kiwi' ]
```

It's due to the `String.prototype.localeCompare` method, which adjusts to the locale and environment.

### **Object Sorting: Managing Your Digital Shop**

Have a product array?

```javascript
const merchandise = [
  { name: 'Laptop', price: 1000 },
  { name: 'Mouse', price: 20 },
  { name: 'Keyboard', price: 50 }
];
```

Sort by cost effortlessly:

```javascript
merchandise.sort((a, b) => a.price - b.price);
console.log(merchandise);
// Output: [{ name: 'Mouse', price: 20 }, { name: 'Keyboard', price: 50 }, { name: 'Laptop', price: 1000 }]
```

### **Advice and Warnings: The Small Details**

1. **On-the-spot Sorting**: `sort()` modifies the original array. No duplicates here!
2. **Consistency**: Sometimes the sequence remains, sometimes not. It's unpredictable!
3. **Undefined Values**: They always land at the tail end.

### **Conclusion: Sort Like an Expert**

The `Array.prototype.sort()` method is akin to a multi-tool for array sorting in JavaScript. Yes, it has its oddities, particularly with numbers, but with a tailored compare function, you have the reins. Now that you've mastered it, you'll see it as an essential part of your developer toolkit. Enjoy sorting! 🚀