Understanding arrays in JavaScript

Valentine Gatwiri
Nerd For Tech
Published in
2 min readJan 29, 2022

--

An array is the easiest data structure where each data element can be obtained directly by only using its index number.

In JavaScript, the array is a single variable that is used to store different elements.

For example, if we want to store the scores scored by a footballer in 5 games, then there’s no need to define individual variables for each game. Rather, we can define an array that will store the data elements at contiguous memory locations.

  • · array scores[5] defines the scores scored by a footballer in 5 different games where each game scores are located at a particular location in the array
  • e.g marks[0] signifies the scores scored in the first game, marks[1] signifies the scores scored in 2nd game, and so on.

Declaration of an Array
There are two ways to declare an array.
Example:

var Scores= [ ]; // method 1 
var Scores= new Array(); // method 2

sometimes your application might be dealing with a list of objects. For example, the list of products in a shopping list, or the list of colors the user has selected. In situations like that, you use an array to store that list.

Let me show you how. So here I’m going to declare another variable called selected objects.

let selectedObjects=['cup','table','plate'];

Here I am using a meaningful name. I don’t have vr or some other weird name.

Now we can initialize this and set it to an empty array. So the square brackets are what we call array literal. And they indicate an empty array. Now we’ll just initialize this array and add a couple of items like a cup.

Let’s now log this on a console.

console.log(selectedObjects);

When you want to access an element in an array you use an index.

Let’s now specify the index:

console.log(selectedObjects[0]);

JavaScript is a dynamic language. So the type of variables can change at runtime. The same principle applies to our arrays.

So the length of arrays, as well as the type of objects we have in an array are dynamic, they can change.

Let’s initialize this array with three elements to four, we can add another element to this array, so the array will expand.


let selectedObjects=['cup','table','plate'];
selectedObjects[3]='chair';
console.log(selectedObjects);

Conclusion

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. JavaScript arrays are best described as arrays.Arrays use numbers to access its “elements”. JavaScript variables can be objects. Arrays are special kinds of objects.Because of this, you can have variables of different types in the same Array.You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array.

Happy learning!

--

--

Valentine Gatwiri
Nerd For Tech

Just curious.I love solving problems using software development and represent Data in a meaningful way. I like pushing myself and taking up new challenges.