Fixing JavaScript Algorithm Bug: Initializing max with array first element

🐛 A Tiny Bug That Can Break Your Algorithm (And How to Fix It) Recently, I came across a simple JavaScript function to find the maximum number in an array: function findMax(arr) { let max = 0; for (let i = 0; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } It works fine… until you pass an array with all negative numbers: findMax([-10, -3, -50]) // Output: 0 ❌ ❗ The Problem We initialized max with 0. But if all numbers are negative, 0 will always be greater than them — leading to the wrong result. ✅ The Solution Initialize max with the first element of the array instead of 0: function findMax(arr) { let max = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } Now it works correctly: findMax([-10, -3, -50]) // Output: -3 ✅ 💡 Key Takeaway Never assume default values in algorithms. Edge cases (like negative numbers) can silently break your logic. #JavaScript #Programming #SoftwareEngineering #Coding #ProblemSolving #Developers

To view or add a comment, sign in

Explore content categories