A detailed Blog on Arrays in JavaScript

Before We get into how to use arrays in JavaScript, let's first learn what is an array.

Well, an array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number. For instance, if we want to store the marks scored by a student in 5 subjects, then there’s no need to define individual variables for each subject. Rather, we can define an array that will store the data elements at contiguous memory locations. Array marks[5] define the marks scored by a student in 5 different subjects where each subject’s marks are located at a particular location in the array, i.e., marks[0] denote the marks scored in the first subject, marks[1] denotes the marks scored in 2nd subject and so on.

Use Case of an array :

In programming, most of the cases need to store a large amount of data of a similar type. We need to define numerous variables to store such a huge amount of data. While writing the programs, it would be very tough to memorize all variable names. Instead, it is better to define an array and store all the elements in it.

Advantages of Arrays:

  • Arrays represent multiple data items of the same type using a single name.
  • In arrays, the elements can be accessed randomly by using the index number.
  • Arrays allocate memory in contiguous memory locations for all its elements. Hence there is no chance of extra memory being allocated in case of arrays. This avoids memory overflow or shortage of memory in arrays.

image.png

  • Using arrays, other data structures like linked lists, stacks, queues, trees, graphs etc can be implemented.
  • Two-dimensional arrays are used to represent matrices.

Disadvantages of Arrays

  • An array is a static structure (which means the array is of fixed size). Once declared the size of the array cannot be modified. The memory which is allocated to it cannot be increased or decreased.
  • Insertion and deletion are quite difficult in an array as the elements are stored in consecutive memory locations and the shifting operation is costly.
  • Allocating more memory than the requirement leads to wastage of memory space and less allocation of memory also leads to a problem.

Applications of Arrays

  • Array stores data elements of the same data type.

  • Maintains multiple variable names using a single name. Arrays help to maintain large data under a single variable name. This avoid the confusion of using multiple variables.

  • Arrays can be used for sorting data elements. Different sorting techniques like Bubble sort, Insertion sort, Selection sort etc use arrays to store and sort elements easily.

  • Arrays can be used for performing matrix operations. Many databases, small and large, consist of one-dimensional and two-dimensional arrays whose elements are records.

  • Arrays can be used for CPU scheduling.

  • Lastly, arrays are also used to implement other data structures like Stacks, Queues, Heaps, Hash tables etc.

Now that we have a little idea of what an array really is, let's see how to use arrays in JavaScript

Arrays in Javascript

In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements. Declaration of an Array There are basically two ways to declare an array.

//Method 1 :
let num=[]//empty array initialization
//Method 2:
let num = new Array();//empty array initialization

But generally method 1 is preferred over the method 2.

Assigning values to an array:

There are plenty of ways to assign values to an array.

let num=[1,2,3,4,5,6];

Spaces and line breaks are not important. A declaration can span multiple lines:


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

we could also declare an empty array and then add the elements to the array


let num=[];
num[0]=1;
num[1]=2;
num[2]=3;
num[3]=4;
num[4]=5;
num[5]=6;

Array indexes are zero-based: The first element in the array is 0, the second is 1, and so on.

Accessing Array Elements

You access an array element by referring to the index number:

let countries=["india","china","nepal","USA"];

console.log(countries[0])
console.log(countries[1])
console.log(countries[2])
console.log(countries[3])

output:

india china nepal USA

Changing an Array Element:

We can change the value of an array's element by :

let countries=["india","china","nepal","USA"];

countries[1]="france"

output:

india france nepal USA

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements".

Finding the length of an Array :

We use the length keyword to find the length of an array.

For example:

let courses=["python","javascript","golang"];
console.log(courses.length);
**

Output:

3

Sorting an array in javascript:

The sort() method sorts an array alphabetically:

let courses=["python","javascript","golang"];
courses.sort()

Output:

image.png

The reverse() method reverses the elements in an array.

You can use it to sort an array in descending order:

let vegetables=["carrot","cucumber","spinach"];
vegetables.reverse()

Output:

image.png

Numeric Sort:

By default, the sort() function sorts values as strings.

This works well for strings ("Apple" comes before "Banana").

However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce incorrect result when sorting numbers. You can fix this by providing a compare function:

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});

Output:

image.png

Looping/iterating through an array:

We could use any for,while loop to iterate through an array.

For example: Lets try to find the average of all the values stored onto an array.

let marks=[89,99,87,93,95]
let sum=0;

for (let i=0; i<marks.length;i++){
    sum+=marks[i]
    console.log(sum);
}
let avg=sum/5
console.log(`the avg is ${avg}`);

Output:

image.png

But instead of using a traditional for loop, we could also use for.each() loop

The forEach() method calls a function for each element in an array.

The forEach() method is not executed for empty elements.

syntax:

array.forEach(function(currentValue, index, arr), thisValue)

Lets rewrite the above code again with forEach() loop

let sum=0;
const avg = (item,index)=>{
     sum+=marks[index]
     console.log(sum)
}
var marks=[89,99,87,93,95]
marks.forEach(avg)

let ans=sum/5
console.log(`the avg is ${ans}`);

Output:

image.png

JavaScript Array push()

The push() method adds new items to the end of an array.

The push() method changes the length of the array.

The push() method returns the new length.

For example:

let lang=["tamil","telugu","hindi"];
lang.push("english");
console.log(lang);

Output:

image.png

JavaScript Array pop()

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

For example:

let fruits=["apple","orange","tomato","banana"];
fruits.pop() //removes the very last element
console.log(fruits)

Output:

apple orange tomato

JavaScript Array Methods and Properties:

Here is a list of all the available methods in array and their properties for your reference. image.png image.png image.png

Conclusion:

Hope this blog helped you to understand what an array is and its usage and how to use an array in javascript. Use the newly gained knowledge to build more amazing apps. Happy coding. :)