DEV Community

Narmatha
Narmatha

Posted on

ARRAYS IN JAVASCRIPT

Arrays in JavaScript

An array in JavaScript is a special type of object used to store multiple values in a single variable.

For example:
let student1 = "John";
let student2 = "Alice";
let student3 = "David";

we can use an array:

`let students = ["John", "Alice", "David"];

`
Now all three values are stored inside one variable called students.

1. Why Do We Use Arrays?

Arrays are useful when we have a collection of related data.

For example:

let fruits = ["Apple", "Banana", "Mango", "Orange"];

Here, fruits contains four values.

Arrays are commonly used for:

Storing a list of users
Storing products
Storing marks
Storing names
Storing numbers
Storing objects
Processing data with loops and methods.

2. Empty Array

let fruits = [];

You can add values later:

`fruits.push("Apple");
fruits.push("Banana");

console.log(fruits);`

Output:

["Apple", "Banana"]

3.Array Length

The .length property tells you how many elements are in an array.

`let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits.length);
`
Output:

3

Remember:

Index starts at 0, but length counts from 1.

For example:

`Array length = 3

Indexes:
0
1
2
`
The last element can therefore be accessed using:

fruits[fruits.length - 1]

Types of Arrays in JavaScript

JavaScript doesn't have separate built-in array classes for every data type like some languages do. A JavaScript Array can contain different kinds of values.

1. Numeric Array

An array containing numbers:

let numbers = [10, 20, 30, 40, 50];

2. String Array

An array containing strings:

let names = ["John", "Alice", "David"];

3. Boolean Array

An array containing boolean values:

let results = [true, false, true, true];

Top comments (0)