DEV Community

Cover image for Javascript Arrays
Kinanee Samson
Kinanee Samson

Posted on

Javascript Arrays

I know i made an earlier tutorial about some some useful JavaScript array methods that makes working with JavaScript arrays easier, if you missed that , this is the link to it Useful JavaScirpt array Methods
So i realized that i didnt introduce JavaScript arrays and i thought that i should make a proper intro to JavaScript arrays.

What Are Arrays

Arrays are objects that can be used to store a collection of related or unrelated items. Every language has its own implementation of arrays and JavaScript is no different. Think of arrays like a cart where you can put things inside. The items that you put inside of your shopping cart when you go get groceries can be related, or they can be very much unrelated. Say you can put only vegies inside your cart like a carrot, onion, cabbage or you could put vegies, candies and cookies but you get the point now right. Lets look into how JavaScript implements arrays.

JavaScript Arrays

In JavaScript arrays have a proto of object; that is to say that arrays in JavaScript are also objects, however JavaScript arrays have a Symbol.iterator function that sets it out, it is because of this function that we are able to use loop through an array, and we will also look at looping through an array later.

NOTE It is not only arrays that have this Symbol.iterator function in JavaScipt, other objects also have this Symbol.iterator function e.g NodeList and Iterators etc Dont worry about iterators if you dont understand them and Symbol.iterator for now.

Declaring an Array

We can declare an array using the following syntax,

var myArray = []; //you can name the 
//array anything you feel like

Enter fullscreen mode Exit fullscreen mode

it is totally okay to initalize an array to contain no objects like above and then we add objects to the array using an index like below

var myArray = [];
myArray[0] = 2;
myArray[1] = 4;
myArray[2] = 6;

// please note you can store 
//anytype of object in array
myArray[3] = 'Foo';
console.log(myArray) 
//prints out [2, 4, 6, 'foo']
Enter fullscreen mode Exit fullscreen mode

What is an index

An index is a key that we use to access an item in the array. we can't just put items inside our shopping cart lackadasically, we have to arrange them right. So an index allows you to either put an item in a position in an array or retrieve an item at a paticular position from the array. The index of an array is the position of item inside an array, every item has its own index and no two items inside one array can have the same index. The example above uses index to put items inside the array we created. We use square brackets notation to specify the index of an item in an array, The name of the array, followed by square brackets without any space between the name of the array and the square brackets, inside the square bracket is a number that represents the index of the item in the array. we can also do this.

var myArray = [];
myArray[0] = 2;
myArray[1] = 4;
myArray[2] = 6;

let itemOne = myArray[0];
console.log(itemOne) //prints out 2
Enter fullscreen mode Exit fullscreen mode

We used the index to store the the first item in the array in our variable and output that variable to the console. However you might be wondering: Why are we starting from zero. JavaScript uses a zero based index to identify the items in the array, i.e The first item in the array is stored at index 0. you remember base 10 right, starts from zero. so anytime you are working with arrays just remeber that the first item in the array has an index of zero. And you always thought zero was useless right? who is laughing now..
We can also initialize an array and set the items inside the arrays when we create the array.


let myArray = [2, 4, 6, 'foo']; 
//this is also okay too and i 
//suggest you do this rather
// than the first method, 
//however separate different 
//items from each other using 
//a comma, do not forget
//if you dont separate them 
//with a comma, it will result in an error
let itemOne = myArray[0];
 //The first item is still 
//stored at index 0
console.log(itemOne); 
//prints out 2
Enter fullscreen mode Exit fullscreen mode

Finding Items in an array

What if we don't know the index of an item we have in our array and we want to somehow get the index of that item because our code depends on it.. we can use a very useful method that all arrays possess, which is indexOf()

Index Of An Item

we use indexOf() to get the position of an item inside of an array. The function accepts a parameter which is the item we want to get it's index. If the item exists inside of the array, it will return the index of that item as a number however if the item does not exist inside of the array it will return -1. let's see an example

//SYNTAX
array.indexof(item)

var myArray = [2, 3, 4, 'foo', 'bar'];

//let's get the index of foo
var fooIndex = myArray.indexOf('foo');
console.log(fooIndex) //returns 3

// let's get the index of 3
var threeIndex = myArray.indexOf(3);
console.log(threeIndex) //returns 1 
// this proves the zero 
//indexing i was talking 
//about, three is the second
// item, yet it's index is 1

// let's see what happens if
// we try to find something
// that doesnt exist in the array
var nonExistent = myArray.indexOf('unavialable');
console.log(nonExistent) //returns out -1 because the
// item doesnt exist in the
// array
Enter fullscreen mode Exit fullscreen mode

Length Of An Array

Normally when we go shopping and we are putting stuffs inside of our cart, we need to keep count of the number of things we have kept inside of our cart right. Similarly we can also keep track of the length of an array i mean we can keep count of the nummber of things we have inside of our array. This is possible because all array have a property called ## length. The number of items in the array is the length of the array and it doesn't follow the zero rule, it starts counting from 1
NOTE the index of the last item of an array is the length of that array - 1. lets see some exapmle

//SYNTAX
array.length

var myArray = [2, 4, 6, 'foo', 'bar'];
var arrayLength = myArray.length;
console.log(arrayLength) //returns 5 because we have 5
// items in the array

var lastIndex = myArray.length -1
console.log(myArray[lastIndex]) //prints out bar
// This length property is 
//useful for looping through the array using a for loop
Enter fullscreen mode Exit fullscreen mode

Pushing items inside of an array

Arrays have a method that make adding items inside of an array easier. It is called..... tada! push()
This method allows us to add a new item to an array. It accepts a parameter which is the item to add to the array, it takes that item and then it adds it after the last element in the array. This method mutates and array, after this method is done excuting, the length of array is updated to account for the item we pushed inside of the array. let's see some examples

//SYNTAX
array.push(item)

var myArray = [2, 4, 6, 8];
console.log(myArray) //[2, 4, 6, 8]
console.log(myArray.length) //prints out 4
console.log(myarray.length - 1) //prints out 8
myArray.push(10)
console.log(myArray) //prints out [2, 4, 6, 8, 10]
console.log(myArray.length) //prints out 5
console.log(myArray.length - 1) //prints out 10
Enter fullscreen mode Exit fullscreen mode

Unshifting Items in an array

We can also add items to the start of an array instead of the end of the array. We use..... unshift() to add a new item to the beginning of an array. This method accepts a parameter which is the item we want to add to the start of the array. This method also mutates an array and updates the length of the array.

//SYNTAX
array.unshift(item)

var myArray = [4, 6, 8, 10];
console.log(myArray) //[4, 6, 8, 10]
console.log(myArray.length) //prints out 4
console.log(myarray[0]) //prints out 4
myArray.unshift(2)
console.log(myArray) 
//prints out [2, 4, 6, 8, 10]
console.log(myArray.length) //prints out 5
console.log(myArray[0]) //prints out 10
Enter fullscreen mode Exit fullscreen mode

Last Words

Arrays in Javascript arrays are refrence type. That is to say that if we have a first variable an array and we have another variable that is equal to the array. any manipulation on the second variable will also change the first array. Let's see

var myArray = [1,3,4]
var newArray = myArray

console.log(newArray) 
//prints out [1, 3, 4]
console.log(myArray) 
//prints out [1, 3, 4]

newArray.unshift(0)

console.log(newArray) 
//prints out [0, 1, 3, 4]
console.log(myArray) 
//prints out [0, 1, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Do well to stay tuned as i will still continue our discussions on array, don't forget to hit the follow button and please drop any question, thoughts and recommendations in the comment section, thank you and have a nice day

Latest comments (0)