JavaScript Array
A JavaScript array is an object that stores a collection of elements of the
same type.
In JavaScript, there are three ways to create an array.
1. Using an array literal.
2. By directly creating an instance of Array (using the
`new` keyword).
3. By using the Array constructor (with the `new` keyword).
JavaScript Array literal
The syntax for creating an array using an array literal is shown below.
Syntax
`let arrayName = [element1, element2, element3, ...];'
As you can see, the values are enclosed within [ ] and separated by commas.
Example
Let’s look at a simple example of creating and using an array in JavaScript.
<Script>
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
</Script>
Output:
apple
banana
cherry
JavaScript Array directly (using keyword)
The syntax for directly creating an array is provided below:
Syntax
`let arrayName = new Array(element1, element2, element3, ...);'
Here, the `new` keyword is used to create an instance of an array.
Example
Let's look at an example of creating an array directly.
<Script>
// Create an array of strings
let colors = ["red", "green", "blue"];
console.log(colors);
</Script>
Output:
["red", "green", "blue"]
JavaScript Array Constructor using new keyword
Here, you create an instance of an array by passing arguments to the
constructor, so you don't need to provide the values explicitly.
The example of creating an object using the Array constructor is provided
below.
Example
<Script>
let myArray = new Array(
{name: "Loid", age: 30},
{name: "Yor", age: 27},
{name: "Anya", age: 6}
);
console.log(myArray);
</Script>
Output:
[
{ name: 'Loid', age: 30 },
{ name: 'Yor', age: 27 },
{ name: 'Anya', age: 6 }
]
JavaScript Array Methods
Let’s review the list of JavaScript array methods along with their
descriptions.