How to reverse an array in two lines with recursion

Think recursion is scary? Reversing an array takes just two lines-and the logic is cleaner than you expect 🎯 Let me break down how recursion reverses an array step by step - this'll change how you think about problem-solving! 💪 𝐓𝐡𝐞 𝐓𝐰𝐨-𝐋𝐢𝐧𝐞 𝐌𝐚𝐠𝐢𝐜: function reverseArray(arr, start = 0, end = arr.length - 1) { if (start >= end) return arr; [arr[start], arr[end]] = [arr[end], arr[start]]; return reverseArray(arr, start + 1, end - 1); } 𝐇𝐞𝐫𝐞'𝐬 𝐭𝐡𝐞 𝐬𝐭𝐞𝐩-𝐛𝐲-𝐬𝐭𝐞𝐩 𝐛𝐫𝐞𝐚𝐤𝐝𝐨𝐰𝐧 𝐭𝐡𝐚𝐭'𝐥𝐥 𝐦𝐚𝐤𝐞 𝐢𝐭 𝐜𝐥𝐢𝐜𝐤: 🎯 𝐁𝐚𝐬𝐞 𝐂𝐚𝐬𝐞 - When start meets or exceeds end, we're done (no more swapping needed!) 🎯 𝐒𝐰𝐚𝐩 - Exchange elements at start and end positions using destructuring 🎯 𝐑𝐞𝐜𝐮𝐫𝐬𝐢𝐯𝐞 𝐂𝐚𝐥𝐥 - Move inward (start+1, end-1) and let recursion handle the rest 𝐖𝐚𝐭𝐜𝐡 𝐢𝐭 𝐰𝐨𝐫𝐤 𝐰𝐢𝐭𝐡 [1,2,3,4,5]: • Call 1: Swap positions 0,4 → [5,2,3,4,1] • Call 2: Swap positions 1,3 → [5,4,3,2,1] • Call 3: start=2, end=2 (base case reached - we're done!) 𝐖𝐡𝐲 𝐭𝐡𝐢𝐬 𝐚𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝐢𝐬 𝐩𝐮𝐫𝐞 𝐠𝐞𝐧𝐢𝐮𝐬: Recursion handles the "unwinding" naturally. Each call focuses on one swap, then trusts the next call to handle the rest. No loops, no complex indexing - just clean, mathematical thinking that reads like English! 🚀 As a React developer, this same recursive pattern shows up everywhere - component trees, state management, you name it. Master it here and watch those concepts become second nature. Drop a ❤️ if this made recursion click for you! #WebDevelopment #JavaScript #Recursion

To view or add a comment, sign in

Explore content categories