Javascript Arrays: The ultimate cheatsheet

Learn what are arrays, array methods and much more.

ยท

10 min read

We all know how to store a value in a variable, but not every time we have this case that we only need to store a single value only. Let's say we want to store the names of students in our class, and there are 50 students in our class. So we need to create 50 variables and store the names of students in them, but won't that be an issue? creating 50 variables, giving them unique names.

So to overcome these issues we are given Arrays in Javascript where we can store many values under a single variable name. We will create an array and store the names of students in that array. Isn't that amazing?

What is an Array?

An array is an ordered collection of one or more values of the same or different data type stored in contiguous memory locations. We can access the elements of the array by specifying the index number of the array.

Declaring an Array

Arrays in Javascript can be declared using 2 different ways:

1. Using an Array literal

This is the most commonly used way to declare an array.

const ArrayName = [item1, item2, item3, ...]

Here ArrayName is the name of the variable in which you want to store all the values.
It is a very common practice to declare an array using the const keyword.

2. Using new keyword

This is a less commonly used way to declare an array due to its complexity and less code-readibility.

const ArrayName = new Array(item1, item2, item3, ...);

Array declaration example

// using array literal
const arr1 = [1, 2, 3, 4, 5, 6];

// using new keyword
const arr2 = new Array(1, 2, 3, 4, 5, 6);

// Array with different data types
const arr3 = [1, "2", true, false, null, undefined, {}, [], () => {}, Symbol()];

Accessing array elements

Array elements can be accessed by referring to their index number.

Indexing

An array is an ordered collection of elements, where elements are ordered according to their index values. Index values of an array start with 0 (which refers to the first array element).
So generalising this, the nth element of an array is referred to by (n-1)th index.

Array elements can be accessed by using the array name and then the index surrounded by the square brackets

// for accessing the (index+1)th element of the array
arrayName[index];

// Accessing array elements
const arr = [1, 2, 3, 4, 5, 6];

console.log(arr[0]); // 1
console.log(arr[1]); // 2
console.log(arr[2]); // 3
console.log(arr[3]); // 4
console.log(arr[4]); // 5
console.log(arr[5]); // 6

Negative indexing

Arrays in javascript support negative indexing. The negative indexing starts from -1 which refers to the last element of the array.
So generalising this, the nth element of an array from the last is referred to by (-n)th index.

// Accessing array elements using negative index
console.log(arr[-1]); // 6
console.log(arr[-2]); // 5
console.log(arr[-3]); // 4
console.log(arr[-4]); // 3
console.log(arr[-5]); // 2
console.log(arr[-6]); // 1

The length property

The length property of an Array returns the number of elements present in it. This is a number one higher than the highest index in the array.

// length property
arrayName.length;

const array = [1, 2, 3, 4, 5, 6];
console.log(array.length); // 6

Updating an Array Element

Javascript arrays are mutable, which means that we can update the values stored in the arrays, no matter if they are declared using const or not we can update their values.

// Updating array elements
const array = [1, 2, 3, 4, 5, 6];

// Reassigning values
array[0] = 'a';
array[1] = 'b';
array[2] = 'c';
array[3] = 'd';
array[4] = 'e';
array[5] = 'f';
console.log(array); // ['a', 'b', 'c', 'd', 'e', 'f']

Adding/Removing elements from an array

We can add or remove elements from start and end both in arrays.

Methods to add or remove elements from the end:

push() Method

The push() method is used to add one or more elements to the end of the array and returns the new length of the array after adding new elements.

// Adding single element to array
const array = [1, 2, 3, 4, 5, 6];
array.push(7); // adds 7 to the end of the array
console.log(array); // [1, 2, 3, 4, 5, 6, 7]

// Adding multiple elements to an array
const arr2 = [1, 2, 3, 4, 5, 6];
arr2.push(7, 8, 9);
console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

// Push method returns new length of array
const return_value = arr2.push(10, 11, 12);
console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
console.log(return_value); // 13

pop() Method

The pop() method is used to remove an element from the end of an array and it returns the value which was removed from the array.

// Pop method
// Removes the last element from an array and returns it
const array = [1, 2, 3, 4, 5, 6];
const removed_element = array.pop();
console.log(array); // [1, 2, 3, 4, 5]
console.log(removed_element); // 6

Methods to add or remove elements from the end:

shift() Method

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

// Shift method
const array = [1, 2, 3, 4, 5, 6];
const removed_element = array.shift();
console.log(array); // [2, 3, 4, 5, 6]
console.log(removed_element); // 1

unshift() Method

The unshift() method adds the element to the starting of an array and returns the new length of the array.

// Unshift method
// Adds new elements to the beginning of an array
const array = [1, 2, 3, 4, 5, 6];
const return_value = array.unshift(0);
console.log(array); // [0, 1, 2, 3, 4, 5, 6]
console.log(return_value); // 7

Looping through arrays

1. For Loop

We can loop through arrays using a for loop which starts with a variable to store the index of the array with the value 0 and the loop will terminate when the value of the variable reaches the length of an array.

// Loop through an array
const array = [1, 2, 3];
for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}
// 1
// 2
// 3

2. For in loop

It gets the key which is used to access the elements of an array.

// for in loop
const array = [1, 2, 3];
for (let i in array) {
  console.log(array[i]);
}
// 1
// 2
// 3

3. For of loop

It is similar to for in loop but instead of the key, it gets the element of the array.

// for of loop
const array = [1, 2, 3, 4, 5, 6];
for (let i of array) {
  console.log(i);
}
// 1
// 2
// 3

Important Array methods

Before starting with these we need to understand what Callback functions are, so let's go learn about callback functions first.

Callback functions

A callback function is a function that is passed into another function(Higher order function) as an argument. This callback function executes during the execution of that higher order function.

const getLarger = (n1, n2) => {
  return n1 > n2 ? n1 : n2;
};

let printMsg = (getLarger, num1, num2) => {
  const larger = getLarger(num1, num2);

  console.log(`The larger number is ${larger}`);
};

// Pass in getLarger as the callback function
printMsg(getLarger, 4, 5);

Learn more about Callback functions

forEach()

The forEach() method executes a callback function for every element of the array in order. It does not return anything, if we try to get the return value we will get undefined.

// forEach method
const array = [1, 2, 3];

array.forEach((element, index) => {
  console.log(`index: ${index}, element: ${element}`);
});

// index: 0, element: 1
// index: 1, element: 2
// index: 2, element: 3

map()

Similar to forEach() method it also executes a callback function for every element of the array in order, but it stores the return value of each element's callback function into an array and returns it.

// map method
const array = [1, 2, 3];
const return_array = array.map((element) => {
  return element * 5;
});

console.log(return_array); // [5, 10, 15]

filter()

It executes a callback function for every element. It returns an array that contains all the elements for which the callback function returned true.

// filter method
const array = [1, 2, 3, 4, 5, 6];
const return_array = array.filter((element) => {
  return element > 3;
});

console.log(return_array); // [4, 5, 6]

reduce()

A callback function with two parameters (accumulator, element) is passed as an argument in this function. For each iteration, the accumulator is the value which is returned by the previous iteration, and the element is the element on a given iteration. Optionally, we can also pass a second argument which will act as the initial value of the accumulator.

// reduce method
const array = [1, 2, 3, 4, 5, 6];

// array.reduce((accumulator, element) => {}, initialValue);

const return_value = array.reduce((accumulator, element) => {
  // accumulator is the calculated value for the array upto now
  // element is the current element in the array
  return accumulator * element;
}, 1);

// 1 * 2 * 3 * 4 * 5 * 6 = 720

console.log(return_value); // 720

reverse()

This method returns an array with the elements in the reverse order, i.e first element becomes last and last becomes first.

// reverse method
const array = [1, 2, 3, 4, 5, 6];
const reverse_array = array.reverse();
console.log(reverse_array); // [6, 5, 4, 3, 2, 1]

some()

This method checks every element for a condition if any element satisfies the condition it returns true. It follows OR gate principle i.e true if any of the input is true. In the given example it checks if the element is greater than 3 since there are elements that satisfy this condition it returns true.

// some method
const array = [1, 2, 3, 4, 5, 6];
const return_value = array.some((element) => {
  return element > 3;
});
console.log(return_value); // true

every()

This method checks every element for a condition like some() but if every element satisfies the condition it returns true else it will return false; It follows AND gate principle, i.e true only if every input is true.

// every method
const array = [1, 2, 3, 4, 5, 6];
const return_value = array.every((element) => {
  return element > 3;
});
console.log(return_value); // false

includes()

This method returns whether the array contains a specific element or not, this method is considered to be good for a quick check but the main drawback of this method is that it checks for strict equality.

// includes method
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const x = 5;
const y = 11;

console.log(array.includes(x)); // true
console.log(array.includes(y)); // false

sort()

As the name suggests, this method receives a function as a parameter and sorts the array according to that function and returns the sorted array.

// sort method
const array = [3, 2, 5, 4, 7];

// Ascending order
const asc_sorted_array = array.sort((a, b) => a - b);
console.log(asc_sorted_array); // [2, 3, 4, 5, 7]

// Descending order
const desc_sorted_array = array.sort((a, b) => b - a);
console.log(desc_sorted_array); // [7, 5, 4, 3, 2]

concat()

This method receives one or more arrays as a parameter and merges them with the original array. It returns the merged array.

// concat method
const array1 = [1, 2, 3];
const array2 = [11, 12, 13];
const array3 = [4, 5, 6];

const array = array1.concat(array2, array3);
console.log(array); // [1, 2, 3, 11, 12, 13, 4, 5, 6]

Thank you for reading, I'll appreciate your feedback and doubts in the comments section if there are any.
Happy Coding ๐Ÿš€

Wishing you all the best for further learning!

Did you find this article valuable?

Support Kunal Yadav by becoming a sponsor. Any amount is appreciated!

ย