Accessing Arrays in JavaScript

Hello Readers!
This episode of the series Basic Data Structure in JavaScript: Arrays includes how to access an array in JS.

Before starting that, we need to know two very important things.

1)JavaScript arrays are zero-based indexed. In other words, the first element of an array starts at index 0, the second element starts at index 1, and so on.

2) How to Get an Array Size.

So, let's start with that.

Getting Array Size with 'length' property

Typically, all arrays have a length property which returns the number of elements or in other words, size of an array.

Let's see an example of an simple one-dimensional array and get it's size.

let petsArr = ['cats','dogs','cows','fishes','birds'];
console.log(petsArr.length);

//output: 5

The output shows 5 as it has five elements occupying five indices from 0 to 4. So the size of this array is 5.

Now, let's see another example of a multi-dimensional array:

let petsArr = [
'cats',['bulldog','husky'],'cows','fishes',
{bird1: 'crow', bird2: 'parrot'}
];
console.log(petsArr.length);

//output: 5

The output is still 5 but it is a complex array which includes another array as it's 3rd element and an JS Object as it's 5th element. But that does not increase the length/size of that array as it is still occupying total 5 indices , from 0 to 4.

Accessing Array Elements

Now let's talk about How to Access the Array Elements in JavaScript.

To access an element in an array, you specify an index in the square brackets [].

The basic syntax is :

arrayName[];

We should not use any spaces between the array name and the square brackets, like array [0]. Although JavaScript is able to process this correctly, but this is not the best practice and this may confuse other programmers reading the code.

The following is a simple example of an one-dimensional array :

let numArr = [50,60,70];

console.log(numArr[0]); //output 50

let data = numArr[1];
console.log(data); //output 60

As arrays are zero-based indexed, the numArr[0] has the value 50 and the data variable stores the value 60 now.

Another example given below is of an multi-dimensional array :

let numArr = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [[10,11,12], 13, 14]
  ];
  console.log(numArr[3]); //output [[10,11,12], 13, 14]
  console.log(numArr[3][0]); //output [10,11,12]
  console.log(numArr[3][0][1]); //output 11

The outputs clearly show how the multi-dimensional array elements are accessed. The index 3 has the value [[10,11,12], 13, 14], as the index 3 holds another array in it's 0 index, numArr[3][0] holds [10,11,12] and the last one simply accessed the data of 1st index of the array [10,11,12] which is 11.

In the next episodes, we will see, how we can modify an array with array indices and other methods as well.

26