JavaScript provides a variety of built-in methods that make it easy to manipulate arrays. Whether you need to add elements, remove them, or transform the entire list, these methods are incredibly powerful.
The most common array tasks involve adding or removing items from the ends or the beginning.
push() adds a new element to the end of an array.pop() removes the last element from an array.const colors = ["Red", "Blue"];
colors.push("Green"); // ["Red", "Blue", "Green"]
colors.pop(); // ["Red", "Blue"]
shift() removes the first element (and "shifts" other
elements down).unshift() adds a new element to the beginning.const colors = ["Red", "Blue"];
colors.shift(); // ["Blue"]
colors.unshift("Green"); // ["Green", "Blue"]
You can convert an array into a single comma-separated string using these methods:
toString() — Converts array to a string with commas.join() — Similar to toString, but you can specify the
separator.const fruits = ["Banana", "Orange", "Apple"];
console.log(fruits.join(" * ")); // "Banana * Orange * Apple"
The splice() method can be used to add new items to an array at any position,
or to remove existing items.
const fruits = ["Banana", "Orange", "Apple"];
// Adds "Lemon" and "Kiwi" at position 2, removes 0 items
fruits.splice(2, 0, "Lemon", "Kiwi");
The concat() method creates a new array by merging (joining) existing arrays.
const arr1 = ["Mim", "Akter"];
const arr2 = ["Redo", "Hub"];
const combined = arr1.concat(arr2);
The slice() method slices out a piece of an array into a new
array. It does not remove any elements from the original array.
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3); // ["Orange", "Lemon"]
push, pop,
splice) modify the original array. However,
slice and concat create a new array instead.
push()/pop() for the end of the arrayshift()/unshift() for the beginning of the arraysplice() is the most versatile for adding/removing at any positionjoin() is more flexible than toString() because you can
choose the separator