An array is an ordered collection of data types that have a numeric index attached to them. Arrays can store any data type, including strings, numbers, and even other objects. The length of an array can be changed after it has been declared.
Arrays are created with a pair of square brackets [ ] around a list of comma-separated values. The first value in the array is at index 0; the second value is at index 1, and so on. Accessing a specific element in an array can be done with square bracket notation as well. Take a look at the following example to see how this works:
Now, let fruits = [‘oranges’, ‘apples’, ‘bananas’];
console.log(fruits); // oranges
console.log(fruits); // apples
console.log(fruits); // bananas
We declared a variable named fruit and set it equal to an array with three different strings inside of it. We then logged the first, second, and third elements to the console using square bracket notation and got back ‘oranges,’ ‘apples,’ and ‘bananas,’ respectively.
As you can see, accessing specific elements in an array is simple once you know how they are indexed.
Adding or removing elements from an array is just as easy using built-in methods that come with every array object. To add an element to the end of an array, you can use the .push() method like this:
Thus, let fruits = [‘oranges’, ‘apples’, ‘bananas’];
console.log(fruits); // [‘oranges’, ‘apples’, ‘bananas’, ‘peaches’]
This adds ‘peaches’ onto the end of our fruits array giving us a new length of 4 items instead of 3. If we wanted to add an element to the start of our fruits array, we could use the .unshift() method like this:
Hence, let fruits = [‘oranges’, ‘apples’, ‘bananas’];
console.log(fruits); // [‘strawberries’, ‘oranges’, ‘apples’, ‘bananas’]
Removing elements from an array works similarly using either .pop() or .shift(). These methods work by taking off and returning the last or first element from an array, respectively, leaving us with a new shorter length for our given array. Check out how this works below:
let fruits = [‘oranges’, ‘apples’, ‘bananas’];
let removedFruit = fruits.pop(); // removes bananas and returns it
console.log(removedFruit); // bananas
console.log(fruits); // [‘oranges’, ‘apples’]
let anotherRemovedFruit = fruits.shift(); // removes oranges and returns it
console,.log(anotherRemovedFruit); // oranges
As you can see, these methods make adding or removing elements from arrays very simple, which comes in handy quite often when working with lists containing data types such as strings or numbers since order matters in those cases.