Javascript Arrays

Arrays in Javascript are a simple, one dimensional way to store simple sets of data. Arrays are non unique, which means they can store duplicates (unlike sets). They also follow typical prototype inheritance, as with other Javascript types. That just m…


This content originally appeared on DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» and was authored by Johnny Simpson

Arrays in Javascript are a simple, one dimensional way to store simple sets of data. Arrays are non unique, which means they can store duplicates (unlike sets). They also follow typical prototype inheritance, as with other Javascript types. That just means that all arrays inherit a certain set of specific methods, like length, some(), every(), concat(), any many more.

Making a Javascript Array

The most straight forward way to create an array is by putting items in square brackets. Each comma separated item is an array element, and the square brackets dictate where the array begins and ends:

let myArray = [ 1, 2, 3, 4, 5, 6 ]

Although this is a common way to define an array, you can also use new Array():

let myArray = new Array(1, 2, 3, 4, 5, 6)

Above we have defined a simple array of 6 items, those being all the numbers from 1 to 6. We have now stored our data in the array format. Similarly we can also store strings, or other standard Javascript types;

let myArray = [ 'hello', 'world' ]
let mySecondArray = [ (hi) => { console.log(hi) }, { some: "Object" }, 1, 2, 3, new Set([1, 2, 3, 4, 4]) ]
let myArray = [ 'πŸ…', '🍊', 'πŸ₯¬', 'πŸ“', '🍠' ]

Getting the length of an array

As mentiond before, all arrays have a standard set of methods which work on them. The most commonly used is perhaps lngth, which we can use to get the size of an array:

let myArray = [ 'πŸ…', '🍊', 'πŸ₯¬', 'πŸ“', '🍠' ]
let getArrayLength = myArray.length; // Returns 5, since there are 5 items.

Accessing properties in an array

Arrays are basically objects in Javascript, where every element is indexed by a number. As such, we can access array elements using the obj[key] method as we do in objects, where key will always be a number.

As with other languages, we usually start counting at 0, so the first item has an index of 0, and as such the second item has an index of 1. To access the second item, we may do this:

let myArray = [ 'πŸ…', '🍊', 'πŸ₯¬', 'πŸ“', '🍠' ]
let getOrange = myArray[1] // Returns 🍊

Getting the last element of an array

Since we know the length of an array, we can use that information to get the last element in an array. That looks a bit like this

let myArray = [ 'πŸ…', '🍊', 'πŸ₯¬', 'πŸ“', '🍠' ]
let getArrayLength = myArray.length // Returns 5, since there are 5 items.
let getOrange = myArray[getArrayLength-1] // Returns 🍠

Another easy way to do this is to just use the at method:

let myArray = [ 'πŸ…', '🍊', 'πŸ₯¬', 'πŸ“', '🍠' ]
let getOrange = myArray.at(-1) // Returns 🍠

Iterating over an array

Another important feature of arrays is they are iterable. That means they work with any function expecting an iterable, or within for loops. Using for loops are an easy way to iterate over every item in an array. In the below example, we will console log every array item:

let myArray = [ 'πŸ…', '🍊', 'πŸ₯¬', 'πŸ“', '🍠' ]
for(let i = 0; i < myArray.length; ++i) {
    // Since i changes +1 every time, the below line will be run for every array item
    // Thus every array item will be console logged for us.
    console.log(myArray[i])
}

You may also see this written like this, which turns i into the array element itself:

let myArray = [ 'πŸ…', '🍊', 'πŸ₯¬', 'πŸ“', '🍠' ]
for(let i of myArray) {
    console.log(i)
}

One more loop which you might find useful is in the form let i in myArray, which instead of returning the array element returns the key for that array element:

let myArray = [ 'πŸ…', '🍊', 'πŸ₯¬', 'πŸ“', '🍠' ]
for(let i in myArray) {
    console.log(myArray[i])
}

Turning strings into arrays

If we have a string separated by a specific character, we can split it into an array. Imagine we have all of our fruit and vegetables in a string separated by '-'. If we apply the splitfunction to that string, we will get an array:

let myString = "πŸ…-🍊-πŸ₯¬-πŸ“-🍠";

// Returns [ 'πŸ…', '🍊', 'πŸ₯¬', 'πŸ“', '🍠' ]
let myArray = myString.split('-');

Manipulating existing arrays

Since arrays can be modified after they are created, we have a number of methods and oprators available to modify them. For example, using the three dots operator we can easily merge two arrays:

let array1 = [ 'πŸ…', '🍊' ]
let array2 = [ 'πŸ…', '🍊' ]
let array3 = [ ...array1, ...array2 ] // [ 'πŸ…', '🍊', 'πŸ…', '🍊' ]

To add or remove elements from each end of an array, we have 4 methods - push, pop, shift and unshift.

push

We can also add new items to an array using the push method, which adds one item at the end of an array:

let array = [ 'πŸ…', '🍊' ]
array.push('πŸ₯¬')
console.log(array) [ 'πŸ…', '🍊', 'πŸ₯¬' ]

pop

If we wanted to instead remove the last element of an array, we can use pop():

let array = [ 'πŸ…', '🍊' ]
array.push('πŸ₯¬')
array.pop()
console.log(array) // [ 'πŸ…', '🍊', 'πŸ₯¬' ]

unshift

Similarly, we can add items to the start of an array using unshift. This is slower than push, since it requires moving everything to one side as well as inserting an item.

let array = [ 'πŸ…', '🍊' ]
array.unshift('πŸ₯¬')
console.log(array) [ 'πŸ₯¬', 'πŸ…', '🍊' ]

shift

If unshift is to push, then pop is to shift - we can use shift to remove the first element of an array:

let array = [ 'πŸ…', '🍊' ]
array.shift()
console.log(array) [ '🍊' ]

Conclusion

Arrays are really important in Javascript. Understanding how they work is crucial in understanding Javascript. Although they can seem daunting, the important things to remember are:

  • Javascript arrays can be defined with square brackets [] or new Array()
  • Arrays can contain any standard Javascript types, for example - functions, objects, or sets.
  • Arrays are essentially objects - each array element is given a numbered index allowing us to access it with obj[key] notation
  • Arrays are iterable, meaning they can be iterated on in for loops.
  • Arrays have a number of standard methods and properties, for example - split(), concat(), some(), pop(), shift() and length.


This content originally appeared on DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» and was authored by Johnny Simpson


Print Share Comment Cite Upload Translate Updates
APA

Johnny Simpson | Sciencx (2023-02-04T23:16:00+00:00) Javascript Arrays. Retrieved from https://www.scien.cx/2023/02/04/javascript-arrays/

MLA
" » Javascript Arrays." Johnny Simpson | Sciencx - Saturday February 4, 2023, https://www.scien.cx/2023/02/04/javascript-arrays/
HARVARD
Johnny Simpson | Sciencx Saturday February 4, 2023 » Javascript Arrays., viewed ,<https://www.scien.cx/2023/02/04/javascript-arrays/>
VANCOUVER
Johnny Simpson | Sciencx - » Javascript Arrays. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/02/04/javascript-arrays/
CHICAGO
" » Javascript Arrays." Johnny Simpson | Sciencx - Accessed . https://www.scien.cx/2023/02/04/javascript-arrays/
IEEE
" » Javascript Arrays." Johnny Simpson | Sciencx [Online]. Available: https://www.scien.cx/2023/02/04/javascript-arrays/. [Accessed: ]
rf:citation
» Javascript Arrays | Johnny Simpson | Sciencx | https://www.scien.cx/2023/02/04/javascript-arrays/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.