Menu
Coddy logo textTech

Array Methods Part 1

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 60 of 77.

Arrays are packed with many methods (functionalities). To access a method, write:

someArray.method()

Here is a list of the basic methods:

  • push(element) - adds an element to the end of the array
  • pop() - removes an element from the end of the array and returns it
  • shift(element) - removes an element from the beginning of the array and returns it
  • unshift(element) - adds an element to the beginning of the array

Here is an example of how to use the push method:

let myArray = ["orange", "banana", "apple"];
myArray.push("strawberry");
console.log(myArray);

This will output ["orange", "banana", "apple", "strawberry"].

Example of the pop method:

let myArray = [1, 2, 3, 4, 5];
let lastElement = myArray.pop();
console.log(myArray);
console.log(lastElement);

This will output [1, 2, 3, 4] and 5.

Example of the shift method:

let myArray = [1, 2, 3, 4, 5];
let firstElement = myArray.shift();
console.log(myArray);
console.log(firstElement);

This will output [2, 3, 4, 5] and 1.

Example of the unshift method:

let myArray = [1, 2, 3, 4, 5];
myArray.unshift(0);
console.log(myArray);

This will output [0, 1, 2, 3, 4, 5].

challenge icon

Challenge

Easy

Create a function named swapEnds that receives one argument:

  • An array

The function swaps the first and the last elements of the array and returns the modified array.

For example with the following arguments: swapEnds([1, 2, 3, 4]) the function will return [4, 2, 3, 1]

Cheat sheet

Arrays have methods to add and remove elements:

  • push(element) - adds an element to the end of the array
  • pop() - removes an element from the end of the array and returns it
  • shift() - removes an element from the beginning of the array and returns it
  • unshift(element) - adds an element to the beginning of the array

Examples:

let myArray = ["orange", "banana", "apple"];
myArray.push("strawberry"); // ["orange", "banana", "apple", "strawberry"]

let lastElement = myArray.pop(); // returns "strawberry"
let firstElement = myArray.shift(); // returns "orange"
myArray.unshift("grape"); // adds "grape" to beginning

Try it yourself

function swapEnds(arr) {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals