
In this tutorial, you will know about JavaScript Arrays.
JavaScript Arrays are used to store multiple values. It is used when we want to store a list of elements and access them with the help of a single variable. JavaScript Arrays can store elements of any data type. This feature is not available in most programming languages.
for example
const student = [“Student1”, “Student2”, “Student3”];
student
is an array which is storing three values of the same data type.
Declaration of Arrays
Arrays can be declared by two methods:
- let arr1 = [];
- let arr2 = new Array();
Initially, the arrays are empty. the first method is always preferred over the second method.
Initialization of Arrays
- Initialization of first method
let arr = [10, 20, 30, 40, 50];
Also we can create an array like below:
let arr = [];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
//Empty array
const arr1 = [ ];
// array of numbers
const arr2 = [ 12, 24, 36, 48];
// array of strings
const arr3 = [ 'apple', 'banana', 'mango'];
// array of mixed data types element
const arr4 = ['apple', 'number', 11, false];
- Using the new keyword
let arr = new Array(10, 20, 30, 40, 50);
Here , we are creating a array which is initialized while declaration time.
let arr = new Array(5);
This array initially contain undefined elements inside it. We can initialized it like the first method.
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
//Empty array
const arr1 = new Array();
// array of numbers
const arr2 = new Array(12, 24, 36, 48);
// array of strings
const arr3 = new Array('apple', 'banana', 'mango');
// array with mixed data types
const arr4 = new Array('apple', 'number', 11, false);
Access the array element
An array element can be accessed by the index number. The index always starts from 0.
syntax:
arrayname[ indexnumber ]
arr[0] –> this points to the first element of array arr.
for example:
let arr = [];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
console.log(arr[0]); // 10
console.log(arr[1]); // 20
console.log(arr[2]); // 30
console.log(arr[3]); // 40
console.log(arr[4]); // 50
Array length
There is the function name length is used to find the length of an array, i.e., the total number of elements in an array.
const arr1 = new Array('apple', 'banana', 'mango');
console.log(arr1.length); // 3
How do change the Elements of an Array?
Array elements can be changed by accessing the index of an element.
const arr1 = new Array('apple', 'banana', 'mango');
arr1[0] = 'orange';
console.log(arr1);

Sort the array element
using the sort()
method
const arr1 = new Array('apple', 'banana', 'mango');
arr1[0] = 'orange';
arr1.sort();
console.log(arr1);

Article Written By:: Ankita Kataria.
Check about Synchronous and Asynchronous JavaScript.
#JavaScript Arrays
Thank you !!