JavaScript Array Methods

Converting Arrays to Strings

The JavaScript method toString() converts an array to a string of (comma separated) array values.

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

Result:

Banana,Orange,Apple,Mango

The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator:

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");

Result:

Banana * Orange * Apple * Mango

Popping and Pushing

When you work with arrays, it is easy to remove elements and add new elements.

This is what popping and pushing is:

Popping items out of an array, or pushing items into an array.



Popping

The pop() method removes the last element from an array:

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();  // Removes "Mango" from fruits

The pop() method returns the value that was "popped out":

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let x = fruits.pop();  // x = "Mango"

Pushing

The push() method adds a new element to an array (at the end):

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");   // Adds "Kiwi" to fruits