Introduction to Arrays and Array Methods in JavaScript

·

6 min read

Arrays, in JavaScript, allow storing several items under a variable name. In addition, they allow for various array methods, which can manipulate or alter the stored data in multiple ways.

How can one identify an array in JavaScript? A simple way of remembering is through the square brackets [], containing items, which can be a single data type or a combination of several types separated by a comma. The data types can be strings, arrays, objects, numbers, Booleans, or a combination.

The syntax of an array is as follows:

const arr_name = [first_item, second_item, third_item,............., last_item];

Characteristics of Arrays in JavaScript

  1. They can be resized. That means the length can be increased through several methods, such as push.
  2. They can be a combination of multiple data types
  3. They are not associative, which implies it is impossible to access them using arbitrary strings but, instead, can be accessed through positive integers as indexes.
  4. JavaScript arrays start from index 0.
  5. Their copy operations result in shallow copies, implying that they share the same properties with the parent source.

Creating an Array

There are several ways of creating a new array, with the word ‘new’ or without. Notably, both approaches will create your desired array. That is illustrated as follows;

  • Using the Array constructor
    const cars = new Array ("Toyota", "Volvo", "Audi", "BMW");
    console.log(cars)
    

Output:

["Toyota", "Volvo", "Audi", "BMW"]
  • Using the literal notation.

Similarly, the same array can be created using the literal notation as follows:

const cars = ["Toyota", "Volvo", "Audi", "BMW"];
console.log(cars)

Output:

["Toyota", "Volvo", "Audi", "BMW"]
  • Using the Array constructor containing one parameter. The length property of an array comes into play when constructing an array using this method. The array is formed by inputting the array's length as the parameter.
const cars = new Array (4)

Assess the length of the array: console.log(cars. Length);

Output

4

Notably, there are no elements in the array, and accessing the index of any of them will output undefined.

console.log(cars[1];

Output

undefined

How to Access an Element in an Array.

Any element of an array can be accessed using its index. As noted earlier, JavaScript arrays start from index 0. That is illustrated in the example below.

const cars = ["Toyota", "Volvo", "Audi", "BMW"];
console.log(0);
console.log(1);
console.log(2);
console.log(3);

Output:

Toyota
Volvo
Audi
BMW

Array Methods

The following are some of the methods that you may encounter in your development journey. Every method works differently from each other and is designed to perform specific functions on arrays.

Array.isArray()

The method confirms whether a given value is an array or not. For instance, you may want to confirm if the above example of cars is an array. The return value is a Boolean value, either false or true.

console.log (Array.isArray(cars));

Output

true

join()

The join method is used to create a string through concatenation of all the elements contained inside the array. In the event that you have multiple elements in your array, the return values are separated using a comma.

The join method example is illustrated as follows.

const students= ['Jane', 'John', 'Peter'];
console.log(students.join()); // "Jane,John,Peter"

The joining of the elements can be done in various ways. This is illustrated in the code below:

students. Join(); //"Jane,John,Peter"
students.join(', ');//”Jane, John, Peter”
students.join(' + '); //”Jane + John + Peter”
Students.join (''); //”JaneJohnPeter”

map()

The map method creates a new array, which is the output of the call of a given function, on each element contained in the array. For instance, you may wish to create a new array that contains squared values from the original array's elements. That can be achieved using the map function.

const array1 = [1, 2, 3, 4];
const array2 = array1.map(x=>x**2);
console.log(array2); // [ 1, 4, 9, 16 ]

pop()

The pop method pops out or rather, removes the last element of a given array. It is important to note that the method changes the length of the original array; the returned value is the popped element and not the new array. Where the array is empty, the returned value is always undefined.

const myStack = ['HTML', 'JavaScript', 'Python', 'SQL', 'ReactJs'];
console.log(myStack.pop()); //ReactJS

The new array does not contain the ‘ReactJs’ element

console.log(myStack) //returns [ 'HTML', 'JavaScript', 'Python', 'SQL' ]

push()

The push method adds a new element or multiple elements to the end of an existing array. The returned value contains the new array with added elements. For instance, we may wish to add two more skills to the stack array using the example above.

const myStack = ['HTML', 'JavaScript', 'Python', 'SQL', 'ReactJs'];

Add TypeScript and C

myStack.push('TypeScript', 'C'));
console.log(myStack) //returns [ 'HTML', 'JavaScript', 'Python', 'SQL', 'TypeScript', 'C' ]

slice()

The slice method returns a portion or a shallow copy of the original array, depending on where the start and the end have been specified. Notably, the index of the given items is specified to imply the beginning and end. However, it is essential to note that no modifications are made to the array due to the operation of the slice method.

The method is further explained in the code examples below:

const subjects= ['Biology', 'Chemistry', 'English', 'Physics', 'Religious Studies'];

console.log(subjects. Slice(2));

The code example returns ['English,' 'Physics,' 'Religious Studies'] because the start index specified was 2, which implies that it slices from English. However, no end condition was specified, meaning that it would return the rest of the array.

console.log(subjects.slice(2, 4));

The example returns an array from English to Physics. That might not be very clear, but it is important to note that the final index specified does not become part of what is returned. The operation above returns the element in indexes 2 and 3, which is ['English', 'Physics'].

console.log(subjects.slice(2, -1));

The code returns the element in index 2, which is English, and the second last element, which is Physics.

shift()

The shift method is the opposite of pop, which removes the last element. Therefore, we expect the shift() method to act completely oppositely. It removes the first element in a given array and returns it. Similarly, it results in a reduction of the overall length of the array.

concat ()

The method is used to merge two or more arrays into a new one, which is the return value. It is important to note that the method differs from the join method, which returns a string.

filter()

The method returns elements in an existing array that meet the specified criteria or pass the condition due to the execution of a given function. It maps through all the elements and returns the elements that meet a given condition.

Conclusion

There are many JavaScript array methods, in addition to the few examples listed above. However, I hope that gives an idea of how the methods work and how they can be used to manipulate, create or modify existing arrays. I will be publishing more content on JavaScript, so stick around🙂