JavaScript Arrays: A Must-Know Tool for Modern Web Development

Gopal Khadka
5 min readOct 5, 2023

--

Photo by Lautaro Andreani on Unsplash

Arrays in JavaScript are a collection of related data items which may have different data types. Unlike variables, it can store and hold multiple items inside it, which can later be accessed and modified using indexing.

It can hold duplicate values, and it is necessary for items to be ordered or sorted. The index of the array starts from zero and index of the last element is one less from the length of the array.

In memory level, items of array occupy contiguous (continuous) memory. Due to this reason, accessing preceding and succeeding value is simpler and easier than in stack and queue.

Creating A New Array

const arr = Array() // first method
console.log(arr) // [] | Empty array

const arr2 = [] // second and preferred method
const fruits = ['apple', 'banana', 'orange'] // array with items

From the above code, we can see that an array can be initialized using two methods, i.e. using Array() object and square brackets. It is usually preferred to use const keyword for arrays so that it remains constant throughout the program.

Finding Length of Array

const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // array of numbers

// Print the array and its length
console.log('Numbers:', numbers) // Numbers: [0, 3.14, 9.81, 37, 98.6, 100]
console.log('Number of numbers:', numbers.length) // Number of numbers: 6

We have used the length attribute of array to find the length of the array. But it is important to remember that index of array starts from zero and to get the final items, we use value of index as 5 (one less than 6).

Indexing Of Array

const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // array of numbers

// Print the array and its length
console.log('Numbers:', numbers) // Numbers: [0, 3.14, 9.81, 37, 98.6, 100]
console.log('Number of numbers:', numbers.length) // Number of numbers: 6

// Getting elements from array
console.log('First item: ',numbers[0]) // 0
console.log('Third item: ',numbers[2]) // 9.81
console.log('last item: ',numbers[5]) // 100

In the above example, we have used an integer value inside square brackets to access the element from the array. This is known as indexing. As said earlier, to get third item (n=3), we use index less than n i.e. index =2.

Adding, Removing and Modifying Values of Array

const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // array of numbers

console.log("First item: ", numbers[0]) // First item: 0
numbers[0] = 1.23 // modifying the first element

numbers.pop() // removes the last item i.e. 100
numbers.push(110) // adds item at last index

console.log(numbers) // [1.23, 3.14, 9.81, 37, 98.6, 110]

We can modify values inside the array using indexing. To remove the last item from an array, we use pop() function. To add an item at the last index of the array, we use push() function and pass the item as argument.

Iterating over Array

const fruits = ['apple', 'banana', 'orange']
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

// Using forEach()
fruits.forEach(function(fruit) {
console.log(fruit);
});

We use normal for loop and forEach loop to iterate or loop over the array. We can do any action after iterating over the array.

Finding Index of the Item

const fruits = ['banana', 'orange', 'mango', 'lemon']
let index = fruits.indexOf('banana') // 0

if(index === -1){
console.log('This fruit does not exist in the array')
} else {
console.log('This fruit does exist in the array')
}

The <array>.indexof(item) function helps to find the index of an item in the array if it exists. It returns the index of the item if it exists, and returns -1 if it doesn’t exist. Another thing to remember while using this function is it only returns the first index of the duplicate items in the array.

But if you want to get the last index of the item in the array, your code look like this:

const numbers = [1, 2, 3, 4, 5, 3, 1, 2]

console.log(numbers.lastIndexOf(2)) // 7 i.e 8th item
console.log(numbers.lastIndexOf(0)) // -1
console.log(numbers.lastIndexOf(1)) // 6
console.log(numbers.lastIndexOf(4)) // 3
console.log(numbers.lastIndexOf(6)) // -1

The <array>.lastIndexof(item) function helps to find the last index of an item in the array if it exists. It returns the index of the item if it exists, and returns -1 if it doesn’t exist.

Checking Array

const numbers = [1, 2, 3, 4, 5]
console.log(Array.isArray(numbers)) // true

const number = 100
console.log(Array.isArray(number)) // false

The Array.isArray(<array>) returns boolean after checking if <array> is actually an array or not.

Converting Array to String

const numbers = [1, 2, 3, 4, 5]
console.log(numbers.toString()) // 1,2,3,4,5

console.log(Array.isArray(number)) // true

The <array>.toString() returns array in the form of string, but doesn’t convert the original array into string type. Another way to achieve this is to use <array>.join(separator) function and convert all items into a string, separated by a separator. The default separator is comma(,).

const webTechs = [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB'
] // List of web technologies

console.log(webTechs.join()) // "HTML,CSS,JavaScript,React,Redux,Node,MongoDB"
console.log(webTechs.join(' # ')) // "HTML # CSS # JavaScript # React # Redux # Node # MongoDB"

Concatenating Two Arrays

const firstList = [1, 2, 3]
const secondList = [4, 5, 6]
const thirdList = firstList.concat(secondList)

console.log(thirdList) // [1, 2, 3, 4, 5, 6]

Concatenation in programming means joining. We use <array1>.concat(<array2>) to join two arrays without modifying both original arrays. So, we have stored joined arrays in the third list.

Slicing Arrays

  const numbers = [1,2,3,4,5]

console.log(numbers.slice()) // -> it copies all item
console.log(numbers.slice(0)) // -> it copies all item
console.log(numbers.slice(0, numbers.length)) // it copies all item
console.log(numbers.slice(1,4)) // -> [2,3,4] // it doesn't include the ending position

The <array>.slice(start,end) function helps to slice or cut the array into sub arrays. The default values of start and end are 0 and length of array respectively. The important thing to remember is that start value is inclusive while end value is exclusive.

So, the item at index of end value won’t be included in the sub array. So in the last line of code, “5” is not included in the sub array because its index is 4.

This concludes the basic understanding of arrays in JavaScript. Arrays are very important concepts in web developments as all the elements are represented in form of array or list while manipulating DOM of web page.

--

--

Gopal Khadka

Aspiring coder and writer, passionate about crafting compelling stories through code and words. Merging creativity and technology to connect with others.