JavaScript Array Manipulation Methods
JavaScript provides several methods to copy, merge, remove, and insert array elements. These methods are commonly used when working with arrays in JavaScript.
In this article, you will learn:
- concat()
- slice()
- splice()
- delete operator
Array concat()
The concat() method joins two or more arrays and returns a new array.
It does not modify the original arrays.
Syntax
array1.concat(array2, array3, …)
Parameters
- array2, array3… → Arrays or values to join.
Return Value: Returns a new merged array.
Example
let frontend = ["HTML", "CSS"];
let backend = ["JavaScript", "Node.js"];
let courses = frontend.concat(backend);
console.log(courses);Output
[“HTML”, “CSS”, “JavaScript”, “Node.js”]
Array slice()
The slice() method returns a selected portion of an array.
It does not modify the original array.
Syntax
arrayName.slice(start, end)
Parameters
- start → Starting index (included).
- end → Ending index (excluded). Optional.
Return Value: Returns a new array.
Example
let fruits = ["Apple", "Banana", "Mango", "Orange"];
let result = fruits.slice(1, 3);
console.log(result);Output
[“Banana”, “Mango”]
Array splice()
The splice() method adds, removes, or replaces elements in an array.
It changes the original array.
Syntax
arrayName.splice(start, deleteCount, item1, item2, …)
Parameters
- start → Index where the operation begins.
- deleteCount → Number of elements to remove.
- item1, item2… → Elements to insert (optional).
Return Value: Returns an array containing the removed elements.
Example 1: Remove Elements
let fruits = ["Apple", "Banana", "Mango", "Orange"];
fruits.splice(1, 2);
console.log(fruits);Output
[“Apple”, “Orange”]
Example 2: Add Elements
let fruits = ["Apple", "Orange"];
fruits.splice(1, 0, "Banana", "Mango");
console.log(fruits);Output
[“Apple”, “Banana”, “Mango”, “Orange”]
Array delete Operator
The delete operator removes an element from an array.
However, it does not remove the index. Instead, it leaves an empty slot in the array.
Because of this, using splice() is usually a better choice.
Syntax
delete arrayName[index]
Example
let fruits = ["Apple", "Banana", "Mango"];
delete fruits[1];
console.log(fruits);
console.log(fruits.length);Output
[“Apple”, empty, “Mango”]
3
Method Comparison
| Method | Purpose | Changes Original Array |
| concat() | Merge arrays | No |
| slice() | Copy part of an array | No |
| splice() | Add, remove, or replace elements | Yes |
| delete | Remove an element | Yes (leaves an empty slot) |