An array is an object that can store a collection of items. Arrays become really useful when you need to store large amounts of data of the same type. Suppose you want to store details of 500 employees. If you are using variables, you will have to create 500 variables whereas you can do the same with a single array. You can access the items in an array by referring to its indexnumberand the index of the first element of any array is zero.
Creating an Array
You can create an array in JavaScript as given below.
1
| var students = [ "John" , "Ann" , "Kevin" ]; |
Here, you are initializing your array as and when it is created with values “John”, “Ann” and “Kevin”.The index of “John”, “Ann” and “Kevin” is 0, 1 and 2 respectively. If you want to add more elements to the students array, you can do it like this:
1
2
| students[3] = "Emma" ; students[4] = "Rose" ; |
You can also create an array using Array constructor like this:
1
| var students = new Array( "John" , "Ann" , "Kevin" ); |
OR
1
2
3
4
5
6
7
| var students = new Array(); students[0] = "John" ; students[1] = "Ann" ; students[2] = "Kevin" ; |
Properties and Methods
The Array object has many properties and methods which help developers to handle arrays easily and efficiently. You can get the value of a property by specifying arrayname.property and the output of a method by specifying arrayname.method().
- length property --> If you want to know the number of elements in an array, you can use the length property.
- prototype property --> If you want to add new properties and methods, you can use the prototype property.
- reverse method --> You can reverse the order of items in an array using reverse method.
- sort method --> You can sort the items in an array using sort method.
- pop method --> You can remove the last item of an array using pop method.
- shift method --> You can remove the first item of an array using shift method.
Try this yourself: