Introduction
When working with JavaScript, developers often get confused between slice(), splice(), and split(). While they sound similar, they serve completely different purposes.
In this article, you'll learn the exact difference, when to use each method, and see working examples you can apply in real projects.
1. slice() – Extract Without Changing Original Array
The slice() method is used to extract a portion of an array without modifying the original array.
Syntax
array.slice(start, end)
Example
let employee = ['Bala','Rahul','Rohit','Vicky'];
let result = employee.slice(1,3);
console.log(result);
console.log(employee);
Output:
[ 'Rahul', 'Rohit' ]
[ 'Bala', 'Rahul', 'Rohit', 'Vicky' ]
Key Points
- Does NOT modify original array
- Returns a new array
- End index is NOT included
2. splice() – Modify Original Array
The splice() method is used to add, remove, or replace elements in an array.
Syntax
array.splice(start, deleteCount, item1, item2, ...)
Example
let employee = ['Bala','Rahul','Rohit','Vicky'];
employee.splice(1,1,'Jack');
console.log(employee);
Output:
[ 'Bala', 'Jack', 'Rohit', 'Vicky' ]
Key Points:
- Modifies original array
- Can add/remove/replace elements
- Very powerful but must be used carefully
3. split() – Convert String to Array
The split() method is used on strings, not arrays. It converts a string into an array based on a separator.
Syntax:
string.split(separator)
Example:
let employee = "Bala,Rahul,Rohit,Vicky";
let result = employee.split(",");
console.log(result);
Output:
[ 'Bala', 'Rahul', 'Rohit', 'Vicky' ]
Key Points:
- Works on strings
- Returns an array
- Does NOT modify original string
Top comments (0)