JavaScript array is an object that represents a collection of similar type of
elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
Note:Values are contained inside [ ] and separated by , (comma).
Example:
<script>
var emp=["Ramu","Rajesh","Ratan"];
for (i=0;i<[Link];i++)
{
[Link](emp[i] + "<br/>");
}
</script>
Note:The .length property returns the length of an array.
Output:
Ramu Rajesh Ratan
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Example:
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<[Link];i++)
{
[Link](emp[i] + "<br>");
}
</script>
Output:Arun Varun John
3) JavaScript array constructor (new keyword)
You need to create instance of array by passing arguments in constructor so that
we don't have to provide value explicitly.
1
Example:
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<[Link];i++)
{
[Link](emp[i] + "<br>");
}
</script>
Output: Jai Vijay Smith
JavaScript Array Methods
Let's see the list of JavaScript array methods with their description.
Methods Description
concat() It returns a new array object that contains two or more
merged arrays.
copywithin() It copies the part of the given array with its own elements
and returns the modified array.
fill() It fills elements into an array with static values.
from() It creates a new array carrying the exact copy of another
array element.
find() It returns the value of the first element in the given array
that satisfies the specified condition.
indexOf() It searches the specified element in the given array and
returns the index of the first match.
join() It joins the elements of an array as a string.
pop() It removes and returns the last element of an array.
push() It adds one or more elements to the end of an array.
reverse() It reverses the elements of given array.
sort() It returns the element of the given array in a sorted order.