Understanding JavaScript Arrays in very simple terms

Understanding JavaScript Arrays in very simple terms

An array in JavaScript is a container that can contain many pieces of information. You can store items like numbers, names, etc. in an array. An array can also contain other arrays. Think of an array as your shopping list or your birthday wish list. Creating an array is as easy as doing this:

var shopping_list=["garri", "pepper", "vegetable"]; //
//we can also create arrays by using the Array() constructor
var shopping_list=new Array("garri","pepper","vegtable");

Items in an array have index numbers. We use index numbers to identify the position of items in an array. In programming, index numbers start from 0 for the first item. In our shopping list, we have three items - garri, pepper, and vegetable. The index numbers for these items are thus 0, 1 and 2 - with garri as 0, pepper as 1, and vegetable as 2.

Quiz: Look at the array below, what is the index of number of "muffins"?

var snack_lis=["cake","pizza","burger","muffins","water"];

If your answer is 3, you're correct.

Adding items to an array

With arrays, you can do so much more than write down your wishes. Let's say your array contains a list of JavaScript frameworks you'd love to learn. How can you add another framework to the list?

//array of my favorite frameworks
var fave_frameworks=["React","vue","svelt"];

JavaScript provides a method for adding items to an array. This method is the .push() method. With the .push() method, you can add other items to your already-created array. Let's say you also want to learn angular, we can also add it to the list using the .push() method. Here's an example:

//adding angular to the list
fave_frameworks.push("angular");

There you go. You can see how easy it is to add items to an array.

Removing Items from an array

Removing items from an array is as easy as adding one. You can remove an item from an array using the .pop() method. Let's say you no longer desire angular. Here's how you can take it off the array with the .pop() method:

fave_frameworks.pop();
//removes the angular from the list

NOTE: The pop method only removes the last element in the array.

Conclusion

There are other things you can do with an array like:

1. finding the length of the array;

2. looping over the items in an array, etc.

I hope this helps you in understanding the fundamentals of JavaScript arrays.