ABOUT CONTACT
Prev Page Next Page
Top

JavaScript Array Methods

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

EXAMPLE:

const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars.toString();

➢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 cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars.join(" * ");

RESULT:

Saab * Volvo * BMW

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.

JavaScript Array pop()

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

EXAMPLE:

const cars = ["Saab", "Volvo", "BMW"];
cars.pop();

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

EXAMPLE:

const cars = ["Saab", "Volvo", "BMW"];
let car = cars.pop();

JavaScript Array push()

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

EXAMPLE:

const cars = ["Saab", "Volvo", "BMW"];
cars.push("Volvo");

➢The push() method returns the new array length:

EXAMPLE:

const cars = ["Saab", "Volvo", "BMW"];
let car = cars.push("Volvo");

JavaScript Array shift()

➢The shift() method removes the first array element and "shifts" all other elements to a lower index.

EXAMPLE:

const cars = ["Saab", "Volvo", "BMW"];
cars.shift();

➢The shift() method returns the value that was "shifted out":

EXAMPLE:

const cars = ["Saab", "Volvo", "BMW"];
let car = cars.shift();

JavaScript Array unshift()

➢The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:

EXAMPLE:

const cars = ["Saab", "Volvo", "BMW"];
cars.unshift("Volvo");

➢The unshift() method returns the new array length.

EXAMPLE:

const cars = ["Saab", "Volvo", "BMW"];
cars.unshift("Volvo");

Prev Page Next Page





FEEDBACK

Rating


Message