Creating an array
Let us take some examples of arrays:
An array is an ordered collection of values. Each value in an array is called an element, and each element has a numeric position in an array, known as its index.
In above example, the elements can be accessed as follows:
The elements in an array can be accessed by using their index with square bracket notation. An index is a number that represents the position of an element in an array. The index value starts with 0 and increases by an increment by one. The first position will be
, second will be at
, the third position will be
 and so on. So, array of six elements would have indexes from 0 to 5.
It will result as AppleBananaMango
length property of array. Array length is always greater than the index of any of its elements. Let us take an example of an array to find its length.
It will give the length of array vegetable as 3.
Looping of array elements
When you need to access each element of an array, you can do that with the help of
- for loop using length property of an array
- for-of loop
- for-in loop
Let us take an example of for loops
It result as shown below:
How to add new element to an array?
You can add a new element to an existing array at the end of an array by using
Adding an element to an array
How to remove last element of an array?
You can add a new element to an array, but what about removing an element? The last element of an array can be easily removed by using
It results as
Removing an element from an array
The removed element is given below
The remaining array list after removal of last element
How to add or remove an element at any position of an array?
Just like an element is added or removed at last position by using
pop() method, an element can also be added or removed at any position of an array. This can be achieved by using
splice() method of an array. Its syntax is:
arrayName.splice(startingIndex, deleteCount, Elem1, Elem2,…..ElemN);
The method takes three parameters, the index from where the splicing of an array will occur, second is the deleteCount which specifies how many elements will be removed and the third parameter used to add elements. If you don’t want to delete an element then keep deleteCount as 0. The
splice() method modifies an array. Let us take some examples:
The result of above code is
Removing and inserting element from/in an array
How to extract a portion of an array?
slice() method. In other words, you can say the
slice() method creates a subarray. Its syntax is:
This method takes two parameters as startingIndex at which extraction will be started and an optional endingIndex before which the extraction will be stopped. If endingIndex has not been given, it will extract all the element falling after the startingIndex. Let us take an example to better understand the concept.
Extracting elements from an array