DEV Community

Cover image for Four Fundamental JS Array Methods to Memorize
Miguel C
Miguel C

Posted on

Four Fundamental JS Array Methods to Memorize

There are four basic array methods that every beginner should learn to start manipulating arrays. These methods are push(), pop(), shift(), and unshift(). In this guide, I will take you through each method so that you can start manipulating arrays effectively!

Method push()

The push() method adds an item to the end of an array.

Example

const colorsArray = ["blue", "red", "green"]

colorsArray.push("purple")

console.log(colorsArray)
// Output: ["blue", "red", "green", "purple"]
Enter fullscreen mode Exit fullscreen mode

Image description


Method pop()

The pop() method removes the last item in an array.

Example

const colorsArray = ["blue", "red", "green"]

colorsArray.pop()

console.log(colorsArray)
// Output: ["blue", "red"]
Enter fullscreen mode Exit fullscreen mode

Image description


Method unshift()

The unshift() method adds an item to the beginning of the array.

Example

const colorsArray = ["blue", "red", "green"]

colorsArray.unshift("purple")

console.log(colorsArray)
// Output: ["purple", "blue", "red", "green"]
Enter fullscreen mode Exit fullscreen mode

Image description


Method shift()

The shift() method removes the first item in an array.

Example

const colorsArray = ["blue", "red", "green"]

colorsArray.shift()

console.log(colorsArray)
// Output: ["red", "green"]
Enter fullscreen mode Exit fullscreen mode

Image description


These same methods will work just as well with objects in an array.

Example

const people = [
    {
        name: "Bob",
        age: 23
    },
    {
        name:"Joe",
        age: 55
    }
]

people.push({ name: "Blake", age: 32 }, { name: "Alex", age: 79 });

console.log(people);

// Output: [
//   { name: "Bob", age: 23 },
//   { name: "Joe", age: 55 },
//   { name: "Blake", age: 32 },
//   { name: "Alex", age: 79 }
// ]
Enter fullscreen mode Exit fullscreen mode

Image description


Conclusion

These are the four basic array methods that every beginner should learn to start manipulating arrays. Memorizing these methods is essential and will give you a better foundation as you begin your journey in development.

  • push(): Adds an item at the end of an array.
  • pop(): Removes the last item from an array.
  • unshift(): Adds an item at the beginning of an array.
  • shift(): Removes the first item from an array.

Top comments (0)