JavaScript Array Methods JAVASCRIPT

JavaScript Array Methods  

JavaScript Array Methods

Converting Arrays to Strings

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

Example

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

Arrays to Strings with join()

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

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

JavaScript - pop()

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

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();              // Removes the last element ("Mango") from fruits

JavaScript - push()

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

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");       //  Adds a new element ("Kiwi") to fruits

Slicing an Array

The slice() method slices out a piece of an array into a new array.

Let's take an example of slices out a part of an array starting from array element 1 ("Orange"):

Example

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);

Note: The slice() method creates a new array. It does not remove any elements from the source array.

Array toString()

JavaScript automatically converts an array to a comma-separated string when a primitive value is expected.

This is always the case when you try to output an array.

Example

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

Download free E-book of JAVASCRIPT


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries