Obtaining array length
To obtain the length of an array use array_name.length property.
let fruits = ['Apple', 'Mango', 'Banana'];
console.log(fruits.length)
Output
3
JavaScript Indexed Collections
Indexed collections in JavaScript refer to data structures like arrays, where elements are stored and accessed by numerical indices. Arrays allow for efficient storage and retrieval of ordered data, providing methods for manipulation and traversal of their elements.
Example
an array called ‘student’ contains the names of the students and the index values are the Roll Numbers of the students. JavaScript does not have an explicit array data type. However, we can use the predefined Array object in JavaScript and its methods to work with arrays.
Creating an Array: There are many ways to create and initialize an array that is listed below:
- Creating arrays without defining the array length. In this case, the length is equal to the number of arguments.
Syntax:
let arr = new Array( element0, element1, ... );
let arr = Array( element0, element1, ... );
let arr = [ element0, element1, ... ];
- Creating an array with the given size
Syntax:
let arr = new Array(6);
let arr = Array(6);
let arr = [];
arr.length = 6;
- Create a variable-length array and add many elements as you need.
// First method: Initialize an empty
// array then add elements
let students = [];
students [0] = 'Sujata Singh';
students [1] = 'Mahesh Kumar';
students [2] = 'Leela Nair';
// Second method: Add elements to
// an array when you create it
let fruits = ['apple', ‘mango', 'Banana'];
The methods that can be applied over arrays are:
- Accessing the Array Elements
- Obtaining array length
- Iterating over arrays
- Array Methods