"3 Ways to Move Zeroes in JavaScript Array"

🚀 LeetCode #283 — Move Zeroes (JavaScript Edition) This problem teaches array manipulation, in-place updates, and the pointer technique — perfect for frontend interviews. Below are 3 clear ways to solve it (beginner-friendly). I use both the traditional temp, swap and the modern destructuring so learners can pick what they understand best. 🧩 Approach 1 — One Loop (Swapping Elements) function moveZeroes(nums) { let p = 0; // next position for a non-zero for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { if (i !== p) { // ✅ Only swap when needed let temp = nums[p]; nums[p] = nums[i]; nums[i] = temp; // traditional swap — beginners find this clear } p++; } } return nums; } ⚙️ Possible Minor Improvements You can simplify the code by avoiding the swap when p === i. This avoids unnecessary swapping when the element is already in the correct position. Cleaner version 👇 var moveZeroes = function(nums) { let p = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { if (i !== p) { // ✅ Only swap when needed [nums[p], nums[i]] = [nums[i], nums[p]]; } p++; } } return nums; }; 💡 Why it’s better: When elements are already in order, this avoids unnecessary writes — a small tweak, but cleaner and slightly more efficient! 💬 For learners [nums[p], nums[i]] = [nums[i], nums[p]]; is called Array Destructuring Assignment in JavaScript. Example: [a, b] = [b, a]; It’s a modern, shorter, and cleaner way to swap two values without using a temporary variable. 🧠 Approach 2 — Two Loops (Copy and Fill) function moveZeroes(nums) { let x = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { nums[x] = nums[i]; x++; } } for (let i = x; i < nums.length; i++) { nums[i] = 0; } return nums; } ✅ How it works: The first loop copies all non-zero values to the front (no swapping needed). The second loop fills the remaining positions with zeros. If zeros are already at the end, the second loop just reassigns them — still simple O(n) work. 🔍 Why Use 2 Loops Instead of Swapping? When you use swapping, each non-zero element is moved one by one — even if it’s already in the correct place. The two-loop version just copies forward, making the logic easier to reason about and the code cleaner. 💡 Fun Fact for Learners Both methods run in O(n) time and use O(1) extra space. Using temp is the traditional swap (slight speed boost). Using [a, b] = [b, a] is the modern JS swap. The two-loop version is cleaner when zeros are already near the end. 💬 In short: 👉 Both methods are correct. 👉 The 2-loop version is cleaner and beginner-friendly. 👉 The 1-loop swap version is efficient and teaches in-place thinking. Which one do you prefer — Classic Swap, Modern Destructuring, or Clean Two-Loop? 😄 Let’s discuss in comments 👇 #JavaScript #CodingJourney #FrontendDevelopment #DeveloperTips #LearnByDoing

To view or add a comment, sign in

Explore content categories