JS Array Methods

JavaScript Array Methods: A Beginner's Guide

JavaScript provides a rich set of built-in methods to work with arrays. These methods allow you to easily add, remove, modify, and combine array elements.


1. Converting Arrays to Strings

toString() and join()

toString() and join() Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];

console.log(fruits.toString()); // "Banana,Orange,Apple,Mango" console.log(fruits.join(" * ")); // "Banana * Orange * Apple * Mango"


2. Adding and Removing Elements

push() and pop() (End of Array)

push() and pop() Example

const fruits = ["Banana", "Orange", "Apple"];

fruits.pop(); // Removes "Apple" console.log(fruits); // ["Banana", "Orange"]

fruits.push("Kiwi"); // Adds "Kiwi" to the end console.log(fruits); // ["Banana", "Orange", "Kiwi"]

shift() and unshift() (Start of Array)

shift() and unshift() Example

const fruits = ["Banana", "Orange", "Apple"];

fruits.shift(); // Removes "Banana" console.log(fruits); // ["Orange", "Apple"]

fruits.unshift("Lemon"); // Adds "Lemon" to the beginning console.log(fruits); // ["Lemon", "Orange", "Apple"]


3. Splicing and Slicing Arrays

splice()

The splice() method can be used to add or remove elements from anywhere in an array.

splice() Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];

// At index 2, remove 1 element and add "Lemon" and "Kiwi" fruits.splice(2, 1, "Lemon", "Kiwi");

console.log(fruits); // ["Banana", "Orange", "Lemon", "Kiwi", "Mango"]

slice()

The slice() method slices out a piece of an array into a new array. It does not modify the original array.

slice() Example

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

// Slice from index 1 up to (but not including) index 3 const citrus = fruits.slice(1, 3);

console.log(citrus); // ["Orange", "Lemon"] console.log(fruits); // Original array is unchanged


4. Merging Arrays with concat()

The concat() method creates a new array by merging (concatenating) existing arrays.

concat() Example

const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];

const myChildren = myGirls.concat(myBoys);

console.log(myChildren); // ["Cecilie", "Lone", "Emil", "Tobias", "Linus"]


Exercise

?

Which method adds a new element to the beginning of an array?