JavaScript 101: Arrays, Array Methods and Manipulations-PART I

Creating JS Arrays and Other Methods, i.e., .length, .push(), .pop(), .shift()

Wakoli Votés
10 min readMar 17, 2023

1. Introduction

Arrays are one of the most fundamental and versatile data structures in programming, and in JavaScript, they're used everywhere. Whether you're creating a simple to-do list or a complex web application, understanding how to work with arrays is essential. In this article, we'll cover everything you need to know about arrays and array manipulations in JavaScript. From the basics of declaring and initializing arrays to more advanced operations like iterating over arrays and using powerful array methods, we'll give you the tools you need to level up your programming skills. So, whether you're a beginner or an experienced developer looking to sharpen your skills, read on to master arrays in JavaScript!

  • What are Arrays

Arrays are a fundamental concept in programming that allow us to store and manipulate collections of values. An array is a container that holds a fixed number of values of a specific type, such as numbers, strings, or objects. These values are stored in contiguous memory locations, so they can be easily accessed and manipulated using a single variable name and an index.

Arrays can be used for a wide variety of purposes in programming. For example, you might use an array to store a list of user input values, to keep track of scores in a game, or to represent a collection of data points in a chart. In JavaScript, arrays are especially useful because they can hold values of different data types within a single array.

  • Creating Arrays

In JS, three techniques can be used for creating arrays

var array_name = new Array(array_elements);
var array_name = Array(array_elements);
var array_name = [array_elements];

Let us explain more with the use of specific examples and names.

To declare an array in JavaScript, we use square brackets and separate the values with commas. Here's an example:

const myArray = [1, 2, 3, 4, 5];

In this example, we've created an array called myArray that contains the numbers 1 through 5.

Arrays can be declared with any number of elements, including none. Here's an example of an empty array:

const emptyArray = [];

We can also declare an array with a specific length using the Array() Constructor:

const newArray = new Array(5);

In this example, we've created a new array called newArray with a length of 5. However, because we haven't assigned any values to the array, all the elements will be undefined.

Overall, arrays are a powerful tool in JavaScript that allow us to work with collections of values in a flexible and dynamic way. In the next sections, we'll cover how to manipulate arrays, access specific elements within an array, and use some of the built-in methods provided by JavaScript to make working with arrays even easier.

2. Array Manipulations

  • Adding elements to an array (push, unshift)

When working with arrays in JavaScript, we often need to add, remove, or modify elements within the array. These operations are known as array manipulations, and they are essential for creating dynamic and flexible programs. In this section, we'll cover two common methods for adding elements to an array: push() and unshift(). These methods allow us to add elements to the end and beginning of an array, respectively, and can be especially useful when working with user input or dynamically generated data. Let's dive in!

i. Adding elements to an array with push()

The push() method is a built-in method in JavaScript that allows us to add one or more elements to the end of an array. Here's an example:

const myArray = [1, 2, 3];

myArray.push(4);

console.log(myArray);

// Output: [1, 2, 3, 4]

In this example, we've declared an array called myArray that contains the values 1, 2, and 3. We then use the push() method to add the value 4 to the end of the array. The resulting array contains all four values.

We can also add multiple elements to an array using push(). Here's an example:

const myArray = [1, 2, 3];

myArray.push(4, 5);

console.log(myArray);

// Output: [1, 2, 3, 4, 5]

In this example, we've added two values, 4 and 5, to the end of the array using push().

ii. Adding elements to an array with unshift()

The unshift() method is another built-in method in JavaScript that allows us to add one or more elements to the beginning of an array. Here's an example:

const myArray = [1, 2, 3];

myArray.unshift(0);

console.log(myArray);

// Output: [0, 1, 2, 3]

In this example, we've added the value 0 to the beginning of the array using unshift(). The resulting array contains all four values.

Like push(), we can also add multiple elements to an array using unshift().

Here's an example:

const myArray = [1, 2, 3];

myArray.unshift(-1, 0);

console.log(myArray);

// Output: [-1, 0, 1, 2, 3]

In this example, we've added two values, -1 and 0, to the beginning of the array using unshift().

  • Removing elements from an array (pop, shift)

When working with arrays in JavaScript, we often need to remove elements from the array as well as add them. This can be necessary when working with dynamic data or user input. In this section, we will cover two common methods for removing elements from an array: pop() and shift(). These methods allow us to remove elements from the end and beginning of an array, respectively.

i. Removing elements from an array with pop()

The pop() method is a built-in method in JavaScript that allows us to remove the last element from an array. Here's an example:

const myArray = [1, 2, 3];

myArray.pop();

console.log(myArray);

// Output: [1, 2]

In this example, we've declared an array called myArray that contains the values 1, 2, and 3. We then use the pop() method to remove the last value, which is 3. The resulting array contains only the values 1 and 2.

We can also use pop() to get the value of the removed element. Here's an example:

const myArray = [1, 2, 3];

const removedElement = myArray.pop();

console.log(removedElement);

// Output: 3

console.log(myArray);

// Output: [1, 2]

In this example, we've removed the last element from the array and stored it in a variable called removedElement. We can then use this variable later in our code if needed.

ii. Removing elements from an array with shift()

The shift() method is another built-in method in JavaScript that allows us to remove the first element from an array. Here's an example:

const myArray = [1, 2, 3];

myArray.shift();

console.log(myArray);

// Output: [2, 3]

In this example, we've declared an array called myArray that contains the values 1, 2, and 3. We then use the shift() method to remove the first value, which is 1. The resulting array contains only the values 2 and 3.

We can also use shift() to get the value of the removed element. Here's an example:

const myArray = [1, 2, 3];

const removedElement = myArray.shift();

console.log(removedElement);

// Output: 1

console.log(myArray);

// Output: [2, 3]

In this example, we've removed the first element from the array and stored it in a variable called removedElement. We can then use this variable later in our code if needed.

Overall, pop() and shift() are powerful methods for removing elements from an array in JavaScript. These methods allow us to manipulate arrays and create more dynamic and flexible programs easily.

Let us give a more practical example:

Let's say we have an online store that sells various items, and we want to keep track of the items in our inventory using an array. Here's what the code might look like:

const inventory = ["t-shirt", "jeans", "sneakers", "hat"];

console.log("Inventory before removing items:", inventory);

const removedItem1 = inventory.pop();
const removedItem2 = inventory.shift();

console.log("Inventory after removing items:", inventory);
console.log("Removed items:", removedItem1, removedItem2);

In this example, we start by declaring an array called inventory that contains some items we sell in our store. We then log the original inventory to the console.

Next, we use the pop() method to remove the last item from the inventory array, which in this case is "hat". We store the removed item in a variable called removedItem1.

After that, we use the shift() method to remove the first item from the inventory array, which in this case is "t-shirt". We store the removed item in a variable called removedItem2.

Finally, we log the updated inventory and the removed items to the console so we can see the changes.

By using the pop() and shift() methods, we can easily add or remove items from our inventory as needed. This can be very useful when dealing with dynamic data such as online stores or user input.

  • Accessing elements in an array (indexing, slicing)

Accessing elements in an array is a fundamental operation in JavaScript. We can access elements by their index using bracket notation or extract a subarray using the slice method. In this section, we'll explore how we can use indexing and slicing to access elements in an array using real-life examples.

i. Accessing elements by index

Arrays in JavaScript are zero-indexed, meaning that the first element has an index of 0, the second element has an index of 1, and so on. To access an element in an array, we use the bracket notation and provide the index of the element we want to access. For example:

const shoppingList = ['milk', 'eggs', 'bread', 'bananas'];

console.log(shoppingList[0]);

// Output: 'milk'

console.log(shoppingList[2]);

// Output: 'bread'

In this example, we have an array called shoppingList that contains some items we need to buy. We use bracket notation to access the first element in the array, 'milk', and the third element in the array, 'bread'.

We can also use variables to access elements in an array. For example:

const shoppingList = ['milk', 'eggs', 'bread', 'bananas'];
const index = 1;

console.log(shoppingList[index]); // Output: 'eggs'

In this example, we declare a variable called index that contains the value 1. We then use this variable to access the array's second element, 'eggs'.

ii. Extracting subarrays with slice()

Sometimes, we need to extract a subarray from an existing array. We can do this using the slice() method. The slice() method takes two arguments: the start index and the end index (which is exclusive). Here's an example:

const shoppingList = ['milk', 'eggs', 'bread', 'bananas'];

const breakfastItems = shoppingList.slice(1, 3);

console.log(breakfastItems); // Output: ['eggs', 'bread']

In this example, we use the slice() method to extract a subarray of the shoppingList array that contains the second and third items (eggs and bread), but not the fourth item (bananas). We store the subarray in a variable called breakfastItems and then log it to the console.

We can also use the slice() method to extract a subarray that starts from a certain index and goes all the way to the end of the array. For example:

const shoppingList = ['milk', 'eggs', 'bread', 'bananas'];

const afterEggs = shoppingList.slice(2);

console.log(afterEggs); // Output: ['bread', 'bananas']

In this example, we use the slice() method to extract a subarray of the shoppingList array that contains all the items after the second item (eggs). We store the subarray in a variable called afterEggs and then log it to the console.

Overall, accessing elements in an array is a critical operation in JavaScript, and we can use indexing and slicing to do it efficiently. By using real-life examples like a shopping list, we can see how these operations work in practical situations.

  • Modifying elements in an array (assignment, splice)

Modifying elements in an array is another essential operation, i.e., we can change the value of an existing element in an array or insert or remove elements from a specific index using the splice() method.

Let us explore more:

i. Modifying elements using assignment

To modify an element in an array, we simply assign a new value to the desired index using the assignment operator (=). Here's an example:

const shoppingList = ['milk', 'eggs', 'bread', 'bananas'];

shoppingList[1] = 'cheese';

console.log(shoppingList);

// Output: ['milk', 'cheese', 'bread', 'bananas']

In this example, we have an array called shoppingList, and we want to replace the second item, 'eggs,' with 'cheese.' We do this by assigning 'cheese' to the index 1, which corresponds to the second element of the array.

ii. Modifying elements using splice()

The splice() method is used to add or remove elements from an array. We can use it to insert elements at a specific index, remove them from a specific index, or replace them with new ones. Here's an example:

const shoppingList = ['milk', 'eggs', 'bread', 'bananas'];

shoppingList.splice(2, 1, 'cheese', 'ham');

console.log(shoppingList);

// Output: ['milk', 'eggs', 'cheese', 'ham', 'bananas']

In this example, we use the splice() method to remove the third element, 'bread,' and replace it with two new elements, 'cheese' and 'ham.' The first argument of splice() specifies the index at which to start changing the array, the second argument specifies the number of elements to remove, and the remaining arguments specify the new elements to add.

We can also use the splice() method to remove elements from an array without adding any new ones. Here's an example:

const shoppingList = ['milk', 'eggs', 'bread', 'bananas'];

shoppingList.splice(1, 2);

console.log(shoppingList);

// Output: ['milk', 'bananas']

In this example, we use the splice() method to remove the second and third elements from the shoppingList array. The first argument of splice() specifies the index at which to start changing the array, and the second argument specifies the number of elements to remove.

In both examples, we use a shopping list as a real-life example of how we can modify elements in an array.

Here, we see how easy it is to add, remove, or change elements in an array using JavaScript's built-in methods.

Conclusion and What's Next

In this article, we've covered some essential concepts related to arrays and array manipulations in JavaScript. We started with an introduction to arrays and discussed why they are helpful in programming. We then explored different array manipulation techniques, such as adding and removing elements from an array, accessing elements using indexing and slicing and modifying elements using the assignment and the splice() method.

In the next article, we'll cover the remaining headings, including iterating over arrays using loops, working with multi-dimensional arrays, and common array methods such as map(), filter(), and reduce().

So stay tuned for more!

You can read more on life and other areas on Acceldia’s Home page.

Always happy to connect. Happy Coding!

--

--