Discovering Arrays in JavaScript
Arrays in JavaScipt and methods to access an array
Introduction to arrays in JavaScript
An array is a data structure that can hold a list of elements as an ordered collection. Objects store values as key-value
pairs, which does not guarantee the order of elements. Arrays hold two interesting characteristics,
- It can hold values of mixed types. For example, An array can have elements of type number, string, or object.
- We don’t need to specify the length of the array when initializing it, it’s dynamic.
We can declare and initialize arrays in two different ways; the first is to create variables with empty brackets []
as value, often known as Array literal. The second is the Array constructor, which returns an instance of an array when called. Let’s take a look,
// Array literal
let a = []
// Array constructor from elements
let b = new Array(element0, element1, /* ... ,*/ elementN)
// Array construct from array length
let c = new Array(arrayLength)
Methods of Array
The purpose of an array is to store multiple values in a single entity of a variable. There are different ways in which we can access, add, and delete elements from an array. Let’s have look at them.
push()
Adds one or more elements at the end of an array and return the new length of the array. It does not return a value that has been added to the array.
let a = [] let b = a.push("1") let d = a.push("2") let e = a.push("3") console.log("Output:", e) // Output: 3
pop()
The pop() method is used to remove the last element from an array. It returns the value that has been popped out, unlike push.
Let list = ['cat', 'dog', 'bird'] console.log(list.pop()) // Output: bird
shift()
The shift is similar to
pop
, working on the first element instead of the last. Once the first element is removed, all elements are shifted to a lower index. It returns the element that is shifted out.Let list = ['cat', 'dog', 'bird'] console.log(list.shift()) // Output: cat
unshift()
Unshift methods work opposite to
shift
. It adds elements in first place in the array and shifts all elements to a higher index.Let list = ['cat', 'dog', 'bird'] console.log(list.unshift('reptiles')) // Output: 4
It works similarly to the
push
method, it adds an element and returns the new length of the array.concat()
The concat method creates a new array by concatenating two arrays. It does not modify the existing arrays and always returns a new array.
let list1 = ['red', 'green', 'blue'] let list2 = ['yellow', 'violet', 'orange'] let newList = lest1.concat(list2) console.log(newList) //Output: ['red', 'green', 'blue', 'yellow', 'violet', 'orange']
toString()
The toString method is used to convert an array of elements to a string of elements separated by commas. The method calls
join()
internally which joins array elements with commas separated.const array1 = [1, 2, 'a', '1a']; console.log(array1.toString()); // expected output: "1,2,a,1a"
join()
The join method works the same as toString(). Instead of commas, we can specify a separator to join array elements.
const list = ['red', 'green', 'blue'] console.log(list.join()); // expected output: "red,green,blue" console.log(list.join('')); // expected output: "redgreenblue" console.log(list.join('-')); // expected output: "red-green-blue"
reverse()
This method reverses the array element's position. It changes the original array and swaps the order of the elements.
const list1 = ['one', 'two', 'three']; console.log('Output:', list1); // Output: "list1:" Array ["one", "two", "three"] const reversedList = list1.reverse(); console.log('Reversed Output:', reversedList); // Reversed Output: "reversed:" Array ["three", "two", "one"]
sort()
The
sort
method sorts the elements of an array in ascending order. The performance of the sort depends on implementation.const list1 = ['red', 'green', 'blue']; list1.sort() console.log('Output:', list1); // Output: ['blue', 'green', 'red']
slice()
The slice method returns a new array with removed elements from
startIndex
toendIndex
The original array won’t be modified.
let colors = ['red', 'green', 'blue', 'yellow','orange']; console.log(colors.slice(1,3)); // Output: ['green', 'blue']
Conclusion
We looked at how we can use arrays in JavaScript and some common methods to add, remove, extract and sort elements of arrays. For reading more about arrays, you can check out MDN docs here. It consists of documentation of all the methods available in the Array prototype. We’ll be looking at some implementations in the next few posts. Stay tuned!