array-methods| Dataplexa

Array Methods

Once you start using arrays, you will often need to add items, remove items, or transform existing data.

JavaScript provides built-in array methods that make working with arrays easier and more readable.


What Are Array Methods?

Array methods are predefined functions that allow you to perform common operations on arrays without writing extra logic.

They help you write cleaner and more expressive code.


Adding Elements with push()

The push() method adds a new element to the end of an array.


let fruits = ["apple", "banana"];
fruits.push("orange");
  

The array now contains three elements.


Removing Elements with pop()

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


let items = ["pen", "book", "bag"];
items.pop();
  

This is useful when managing stacks or temporary lists.


Adding to the Beginning with unshift()

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


let queue = ["user2", "user3"];
queue.unshift("user1");
  

The new element becomes the first item.


Removing from the Beginning with shift()

The shift() method removes the first element of an array.


let tasks = ["task1", "task2"];
tasks.shift();
  

This is commonly used in queue-based logic.


Finding Elements with indexOf()

The indexOf() method returns the position of an element. If the element is not found, it returns -1.


let colors = ["red", "blue", "green"];
colors.indexOf("blue");
  

This helps you check whether an item exists in an array.


Real-World Example

Imagine managing a to-do list:


let todos = [];

todos.push("Study JavaScript");
todos.push("Practice coding");
todos.pop();
  

Array methods make list management simple and efficient.


Common Beginner Mistakes

  • Forgetting that methods change the original array
  • Using the wrong method for the desired result
  • Confusing push and unshift

Always understand what a method does before using it.


Thumb Rules

  • Use push() and pop() for stack behavior
  • Use shift() and unshift() for queue behavior
  • Check array contents with indexOf()
  • Keep array operations simple and readable

More on Array Methods Later

This lesson covered the most commonly used array methods for beginners.

More advanced methods are intentionally kept for later lessons.


What Comes Next?

Now that you can work with arrays efficiently, it’s time to understand how JavaScript stores structured data.

In the next lesson, we will learn about objects.