Javascript Arrays
Arrays are simply a data structure to hold multiple data values in a single variable. These are resizeable, heterogeneous, zero-indexed and stored in heap memory.
let myArray = [3, true, "Books", 😊]
// Fixed memory is not allocated here comparing other languages.
// It consists elements of different datatypes.
// For accessing first element we have to write myArray[0].
let newArray = myArray
// Here newArray contains a reference of myArray.We need them to store data in a more organised way with ease of access, so we use Arrays.
These can be created with array constructor and array literal method.
let array1 = [3, 2.5, 9, 12, 63] // It is literal method.
let array2 = Array(3, 5, 4) // It is constructor method.
let array3 = new Array("apple", "ball", "cat"]
let array4 = new Array(3) // It creates array of three empty objects.
// This allocates memory for three elements.
// array4[0] is undefined but array4.length is 3.Accessing and updating array elements
Get Sagar Kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
Arrays elements can be easily accessed and updated as they are zero-indexed.
let fruits = ["Banana", "Mango", "Apple"]
let firstFruit = fruits[0] // Banana
fruits[1] = "Pineapple" // ["Banana", "Pineapple", "Apple"]Arrays have length property which can be used to find the number of elements in an array.
For accessing every elements in an array, we can loop through them.
let fruits = ["Banana", "Mango", "Apple"]
for (let i = 0; i < array.length; i++){
console.log(i); // It prints all elements in an array.
}
let firstElement = fruits[0];
let last element = fruits[fruits.length - 1]








