Javascript Array




Array in javascript is used to hold multiple values in a variable. Javascript Array's can hold variables of different datatypes in a variable.

Example

Where and when can I use Array?

It can be used to store group of variable that belong to same category. Example to hold employees of a company we can create a variable employees and assign all the employee's name inside the square bracket [].

Example

var employees = ['Employee1', 'Employee2','Employee3'];
  

To get the values inside the employees array variable, we can use the index position inside the square bracket. The index will always start with 0. The employee[0] is used to get the first employee name 'Employee1'.

If we want to get all the values inside the employees variable we can loop through the employees variable.

length property:

To get the number of elements inside an array we use length'' property.

Output

3
  

Iterating through an array:

If we want to add a new employee to the list then we can use

Output

Employee1
Employee2
Employee3

Adding an element to an array:

If we want to add an element to the end of the array we use push() method.

Output

["Employee1", "Employee2", "Employee3", "Mark", "John"]

Adding an element to the front of an array:

If we want to add an element to the index position 0 we use unshift() method.

Output

["Paul", "Employee1", "Employee2", "Employee3"]

Adding an element at particular position in an array:

If we want to add an element at a particular position in an array we can use splice() method with 3 arguments.

Output

["Employee1", "John", "Employee2", "Employee3"]

Here in the splice() method, the first argument specifies index position and second argument should be 0 to perform insert operation and third argument is the element to be inserted at the index position specified as the first argument.

Removing an element from an array:

If we want to remove an element at the end of an array we use pop() method.

Output

["Employee1", "Employee2"]

Removing an element from the beginning of an array:

In order to remove an element at the index position 0 we use shift() method.

Output

["Employee2", "Employee3"]

Removing an element at particular index in an array:

If we want to remove an element at particular position in an array we use splice() method.

Output

["Employee1", "Employee3"]

Here the splice() method with 2 parameters is used to remove one element at index position 1.

In our later articles, we shall see advanced functions involved in an array.


Most Read