DEV Community

Cover image for Slice vs Splice vs Split in JavaScript – Key Differences with Real Examples
bala senthil
bala senthil

Posted on

Slice vs Splice vs Split in JavaScript – Key Differences with Real Examples

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)
Enter fullscreen mode Exit fullscreen mode

Example

let employee = ['Bala','Rahul','Rohit','Vicky'];
let result = employee.slice(1,3);
console.log(result);
console.log(employee);
Enter fullscreen mode Exit fullscreen mode

Output:

[ 'Rahul', 'Rohit' ]
[ 'Bala', 'Rahul', 'Rohit', 'Vicky' ]
Enter fullscreen mode Exit fullscreen mode

Key Points

  1. Does NOT modify original array
  2. Returns a new array
  3. 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, ...)
Enter fullscreen mode Exit fullscreen mode

Example

let employee = ['Bala','Rahul','Rohit','Vicky'];
employee.splice(1,1,'Jack');
console.log(employee);
Enter fullscreen mode Exit fullscreen mode

Output:

[ 'Bala', 'Jack', 'Rohit', 'Vicky' ]
Enter fullscreen mode Exit fullscreen mode

Key Points:

  1. Modifies original array
  2. Can add/remove/replace elements
  3. 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)
Enter fullscreen mode Exit fullscreen mode

Example:

let employee = "Bala,Rahul,Rohit,Vicky";
let result = employee.split(",");
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output:

[ 'Bala', 'Rahul', 'Rohit', 'Vicky' ]
Enter fullscreen mode Exit fullscreen mode

Key Points:

  1. Works on strings
  2. Returns an array
  3. Does NOT modify original string

Top comments (0)