JavaScript Array Methods: slice(), splice(), split() Explained

Day 21/50 – JavaScript Interview Question? Question: What is the difference between slice(), splice(), and split()? Simple Answer: slice() extracts a portion of an array/string without modifying the original. splice() adds/removes elements from an array and modifies it in place. split() converts a string into an array based on a delimiter. 🧠 Why it matters in real projects: These are fundamental array and string manipulation methods used daily. slice() is crucial for immutable updates in React/Redux, splice() for in-place modifications, and split() for parsing CSV data, URLs, or user input. 💡 One common mistake: Using splice() when you need immutability (like in React state updates), which causes unexpected mutations. Also confusing slice() and splice() due to similar names. 📌 Bonus: // slice() - extracts without mutation const arr = [1, 2, 3, 4, 5]; const sliced = arr.slice(1, 3); // [2, 3] console.log(arr); // [1, 2, 3, 4, 5] - unchanged // splice() - modifies original array const arr2 = [1, 2, 3, 4, 5]; const removed = arr2.splice(1, 2, 'a', 'b'); console.log(removed); // [2, 3] console.log(arr2); // [1, 'a', 'b', 4, 5] - changed! // split() - string to array const str = "hello-world-test"; const parts = str.split('-'); // ['hello', 'world', 'test'] // React state update - use slice, not splice! setState(prevArr => [...prevArr.slice(0, index), ...prevArr.slice(index + 1)]); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Arrays #WebDev #Coding

To view or add a comment, sign in

Explore content categories