JavaScript Array Methods

Sept 15, 2022

Array Methods

Array Methods

There are many methods on arrays that can be used to make working with them easier. See Array Methods for full details.

.push()

Adds an element to the end of the array.

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

console.log(fruits); // ['Banana', 'Orange', 'Apple', 'Mango', 'Kiwi']

.pop()

Removes an element from the end of the array

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

.unshift()

Adds and element to the beginning of the array

const dice = ['d12', 'd10'];
dice.unshift('d20');

console.log(dice) // ['d20', 'd12', 'd10']

.every()

Returns true if every element passes test function.

const list = [
    { name: 'steak', group: 'meat' },
    { name: 'potato', group: 'vegetable' },
];

const isVegetarian = list.every((item) => !item.group === 'meat');

console.log(isVegetarian); // false

Is false because the steak object did not pass the test

.some()

Returns true if at least one element passes the test function.

const numbers = [1, 2, 3, 4, 5];
const anyEven = numbers.some((number) => number % 2 === 0);

console.log(anyEven) // true

Is true because at least one element is even.

Note that .some() will stop processing the array as soon as it finds one element that passes the test.

.forEach()

Calls a function for every element in the array.

const people = [
    { name: 'Emily', affiliation: 'staff'},
    { name: 'Mike', affiliation: 'faculty'},
];
people.forEach((person) => console.log(person.name));

Output will be

Emily
Mike

More Array Methods

Array Methods