Lesson 3: Array Methods – push(), pop(), length, etc.

Lesson Goal:

Learn how to use built-in array methods to add, remove, and examine elements in a JavaScript array. These methods make array manipulation easy and efficient.


Why Use Array Methods?

Instead of manually updating array elements and indexes, JavaScript provides convenient methods that handle common tasks like adding and removing items from arrays.

Common Array Methods


push()

Adds an item to the end of the array.

let fruits = ["apple", "banana"];
fruits.push("cherry");
console.log(fruits);  // ["apple", "banana", "cherry"]

pop()

Removes the last item from the array and returns it.

let last = fruits.pop();
console.log(last);    // "cherry"
console.log(fruits);  // ["apple", "banana"]

length

Returns the total number of elements in the array.

console.log(fruits.length);  // 2

You can also use length to access the last item:

console.log(fruits[fruits.length - 1]);  // "banana"

shift()

Removes the first item from the array and returns it.

let removed = fruits.shift();
console.log(removed); // "apple"
console.log(fruits);  // ["banana"]

unshift()

Adds an item to the beginning of the array.

fruits.unshift("mango");
console.log(fruits);  // ["mango", "banana"]

Try It Yourself

let cart = ["pen", "notebook"];
cart.push("eraser");
cart.unshift("pencil");
console.log(cart);  // ["pencil", "pen", "notebook", "eraser"]

cart.pop();         // removes "eraser"
cart.shift();       // removes "pencil"
console.log(cart);  // ["pen", "notebook"]

Method Cheat Sheet

MethodDescriptionModifies Original ArrayReturns Value?
push()Add to end✅ Yes✅ Yes
pop()Remove from end✅ Yes✅ Yes
shift()Remove from start✅ Yes✅ Yes
unshift()Add to start✅ Yes✅ Yes
lengthGet number of elements❌ No✅ Yes