JavaScript
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Types
-
Section 3: Strings and Numbers in Depth
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Objects and Arrays
-
Section 7: Maps, Sets, and Symbols
-
Section 8: Asynchronous JavaScript
-
Section 9: Object-Oriented and Prototypes
-
Section 10: The DOM
-
Section 11: Browser APIs
-
Section 12: Modern JavaScript (ES2015-ES2025)
-
Section 13: Functional Programming Patterns
-
Section 14: Error Handling and Debugging
-
Section 15: Testing
-
Section 16: Accessibility for JavaScript Developers
-
Section 17: Internationalization and Localization
-
Section 18: Performance
-
Section 19: Node.js Fundamentals
-
Section 20: Regular Expressions
-
Section 21: Design Patterns in JavaScript
-
Section 22: Security Basics
-
Section 23: Data Structures and Algorithms in JavaScript
-
Section 24: Practical Projects
-
Section 25: More Advanced Async Patterns
-
Section 26: More Object and Class Practice
-
Section 27: Working with Dates and Internationalization
-
Section 28: Web Components
-
Section 29: More DOM and Browser Practice
-
Section 30: Build Tooling for Vanilla JavaScript
-
Section 31: More Practice Projects
-
Section 32: Interview and Algorithm Practice
-
Section 33: Error Objects (MDN Reference)
-
Section 34: TypedArrays and Binary Data
-
Section 35: Reflection and Metaprogramming (MDN Reference)
-
Section 36: More Global Functions (MDN Reference)
46: Sorting and Comparing Arrays
I've seen a lot of junior developers get tripped up by how JavaScript handles arrays, specifically when they start trying to organize or compare them. On the surface, the tools are right there—.sort() and the === operator—but these tools don't always behave the way your intuition tells you they should. If you're coming from a language where == compares the contents of a list, JavaScript is going to throw you a curveball.
The "10 comes before 2" Trap
Let's say you're building a leaderboard for a game. You have an array of scores, and you want to sort them from lowest to highest. The naive move is to just call the sort method:
const scores = [10, 2, 100, 25];
scores.sort();
console.log(scores); // Expected: [2, 10, 25, 100]
// Actual: [10, 100, 2, 25]
It looks broken, right? But here's the thing: JavaScript isn't actually broken; it's just being literal. By default, .sort() converts every element into a string and then compares their UTF-16 code unit values. In a dictionary, "10" comes before "2" because it starts with a "1". It's an annoying quirk, but it's consistent.
To fix this, you have to provide a compare function. This is where you tell JavaScript exactly how to determine the order by returning a number. If the function returns a negative value, a comes first. If it's positive, b comes first. For numbers, the cleanest way to do this is a simple subtraction:
const scores = [10, 2, 100, 25];
scores.sort((a, b) => a - b);
console.log(scores); // [2, 10, 25, 100]
I usually tell my colleagues to just memorize this pattern: (a, b) => a - b for ascending, and (a, b) => b - a for descending. It saves you from having to write a verbose if/else block every time you need to order a list of prices or IDs.
Why your arrays aren't "equal"
Now, let's talk about comparing arrays. You might be tempted to check if two arrays are the same using the strict equality operator. Imagine you're checking if a user's current selection of filters matches a saved preset:
const savedFilters = ['red', 'blue'];
const currentFilters = ['red', 'blue'];
if (savedFilters === currentFilters) {
console.log("They match!");
} else {
console.log("They don't match."); // This will always run
}
This happens because arrays in JavaScript are objects, and objects are compared by reference, not by value. You aren't asking "Do these two arrays have the same items?"; you're asking "Are these two variables pointing to the exact same spot in memory?" Since these are two different array literals, the answer is always no.
If you need to check if the contents are the same, you have to actually look at the elements. For small, simple arrays, I often use the .every() method. It allows you to verify that every single element in the first array matches the element at the same index in the second array. But first, you must check the length—if the lengths differ, there's no point in checking the elements.
const areArraysEqual = (arr1, arr2) => {
if (arr1.length !== arr2.length) return false;
return arr1.every((val, index) => val === arr2[index]);
};
console.log(areArraysEqual(['red', 'blue'], ['red', 'blue'])); // true
You might see people suggest JSON.stringify(arr1) === JSON.stringify(arr2). While that's a quick hack, it's generally a bad habit. It's computationally expensive because it converts the whole array to a string, and it will fail miserably if the order of elements is different but the content is the same. If order doesn't matter to you, your best bet is to sort both arrays first using the method we discussed above, and then run the .every() check.
📋 Practical Task
Exercise: Inventory Sync Validator
You are building a system that syncs inventory lists between a local warehouse and a central server. You need to create a function called syncInventory that takes two arrays of product IDs (numbers) and performs the following steps:
- Sort both arrays in ascending order (lowest ID first).
- Determine if the two sorted arrays are identical in content.
- Return
trueif they match perfectly, orfalseif there is a discrepancy.
Test your function with these cases:
const warehouseA = [501, 102, 305, 202];
const warehouseB = [202, 501, 102, 305];
// syncInventory(warehouseA, warehouseB) should return true
const warehouseC = [501, 102, 305];
const warehouseD = [501, 102, 306];
// syncInventory(warehouseC, warehouseD) should return false
There are no comments for now.