In JavaScript Arrays are an object. You can create Array is JavaScript as following
An array element can be accessed using its index. For example if you want to read banana, you will read that as following,
Likely Array of other languages, JavaScript array index also start from zero. The other way to create JavaScript array is by using the new keyword.
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
Following are the most used functions of JavaScript Array.
Let us explore each functions one by one.
Push Function
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
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
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
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
In further post we will discuss more JavaScript Array functions. I hope you find this post useful. Thanks for reading.
Reblogged this on Sutoprise Avenue, A SutoCom Source.
You are an angel for me. I have wasted my whole night in this problem. m newbie
… thx for the help… Bookmarking it.