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
- By array literal
- By creating instance of Array directly (using new keyword)
- By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
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
Sonoo
Vimal
Ratan
Vimal
Ratan
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
Here, new keyword is used to create instance of array.
Let’s see the example of creating array directly.
Output of the above example
Arun
Varun
John
Varun
John
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 explicitely.
The example of creating object by array constructor is given below.
Output of the above example
Jai
Vijay
Smith
Vijay
Smith
No comments:
Post a Comment