Arrays in JavaScript: Usage and Examples
Table of Content:
JavaScript Array
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];
As you can see, values are contained inside [ ] and separated by , (comma).
Let’s see the simple example of creating and using array in JavaScript.
The .length property returns the length of an array.
Output of the above example
Rumman Ansari Smile
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.
Let’s see the example of creating array directly.
Output of the above example
Rumman Ansari Rambo
3. JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide value explicitly.
The example of creating object by array constructor is given below.
Output of the above example
Azam Inza Master