An array is a special object in JavaScript used to store multiple values in a single variable, where each value is stored at a numbered index starting from 0.
An array is a data structure in JavaScript that stores multiple values in a single variable and allows access to those values using their index positions.
This makes data easier to store, access, update, and process using loops and array methods.
Arrays allow us to organize related data by grouping them within a single variable.
An array can store many values in a single variable, making it easy to access them by referring to the corresponding index number.
In JavaScript, an array is heterogeneous.
What is Heterogeneous?
A heterogeneous array can store different types of data in the same array.
Example
let arr = [10, "Vicky", true, null, {age: 21}];
Here the array contains:
10 → Number
"Vicky" → String
true → Boolean
null → Null
{age: 21} → Object
All are different data types, but JavaScript allows them in the same array.
- JavaScript arrays are heterogeneous because they can store values of different data types in the same array. However, you can also create homogeneous arrays if you choose to store only one type of data.
Example
let fruits = ["Apple", "Banana", "Mango"];
Instead of:
let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Mango";
Arrays are Zero Indexed
Index starts from 0, not 1.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits[2]); // Mango
Array Length
length gives the number of elements.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.length); // 3
Access Elements
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[1]); // Banana
Modify Elements
let fruits = ["Apple", "Banana", "Mango"];
fruits[1] = "Orange";
console.log(fruits);
Output
["Apple", "Orange", "Mango"]
Add Elements
push() → Add at End
let fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits);
Output
["Apple", "Banana", "Mango"]
unshift() → Add at Beginning
fruits.unshift("Orange");
Output
["Orange","Apple", "Banana", "Mango"]
Remove Elements
pop() → Remove from End
let fruits = ["Apple", "Banana", "Mango"];
fruits.pop();
console.log(fruits);
Output
["Apple", "Banana"]
shift() → Remove from Beginning
fruits.shift();
Output
["Banana"]
Arrays store multiple values.
Arrays are zero-indexed.
Arrays are dynamic (size can change).
Arrays can store different data types (heterogeneous).
length gives the number of elements.
push() and pop() work at the end.
shift() and unshift() work at the beginning.
Arrays are technically objects in JavaScript.
References
https://www.w3schools.com/js/js_arrays.asp
https://www.geeksforgeeks.org/javascript/javascript-arrays/
https://www.programiz.com/javascript/array
Top comments (0)