JavaScript Array Methods: Slice vs Splice

🌙 Evening Post — slice vs splice (Same Look, Different Behavior) This morning’s code was: let arr = [1, 2, 3, 4]; let a = arr.slice(1, 3); let b = arr.splice(1, 2); console.log(a); console.log(b); console.log(arr); 💡 Correct Output [2, 3] [2, 3] [1, 4] Yes — the first two lines look the same, but the array changes 👀 Let’s understand why. 🧠 Simple Explanation : 🔹 slice(start, end) Does NOT change the original array Returns a new array end index is not included arr.slice(1, 3) From [1, 2, 3, 4]: Takes index 1 and 2 Returns: [2, 3] Original arr is still: [1, 2, 3, 4] 🔹 splice(start, deleteCount) Changes the original array Removes elements Returns the removed elements arr.splice(1, 2) From [1, 2, 3, 4]: Removes 2 elements starting at index 1 Returns: [2, 3] Now the original array becomes: [1, 4] 🎯 Final Values a → [2, 3] b → [2, 3] arr → [1, 4] 🎯 Key Takeaways : slice() → non-mutating splice() → mutating slice uses end index splice uses delete count 📌 Many bugs happen because developers assume slice and splice are similar. 💬 Your Turn Which one surprised you more? 😄 Comment “slice 😮” or “splice 🤯” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories