An array element can be accessed using its index. For example if you want to read banana, you will read that as following,
You can read elements of array using for loop as following,
You will get following output. You will notice that value of the 5th element in array is undefined since we have not set the 5th element value.
Even though you have set the size of the array as five, you can dynamically increase size of the array. In below listing we are setting value of 10th element. After setting 10th element value size of the array has been increased from 5 to 10.
Since we have not set values from 5th element to 9th element, so those value will be undefined
Let us explore each functions one by one.
Push inserts an element at the top of the array. Suppose we have an array
When you see the console , you will find array elements as following
Now let us push some elements in fruit array . We can push element in the array by calling push function and passing the elements to be inserted as input parameter. In following listing , we are inserting orange and apple in the array. First orange will be inserted then apple.
And as a output you will get array elements as below,
Pop function is used to remove top or last element of the array. From above array we can pop an element as given in below listing
You will find that banana has been removed from the array
unshift function inserts elements in the beginning of the array. Let us suppose we have an array
You can insert elements at the beginning of array using unshift as following
You will find that orange , apple and grapes has been added to the fruits array . Now the first element of the array is grapes.
shift function removes first element from the array. Let us consider this array
when we call shift function on array mango will be removed from the array
You will get array elements printed as following