Javascript Array 101

What is an Array and Why do we need them?
Array is a collection of items that can be the same or different data types stored together. We need arrays because without it we would have to create seperate variables for each item.
For example we have five different fruit,
Without Array:
let fruit1 = "Apple"
let fruit2 = "Banana"
let fruit3 = "Mango"
let fruit4 = "Orange"
let fruit5 = "Grapes"
With Array:
.Array stores each variables in a single variable in a ordered list
let fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"]
How to Create an Array?
//Example 1
let fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"]
//Example 2
const cars = new Array("Saab", "Volvo", "BMW");
Accessing Elements using Index
Array has a position called an index and it start from 0.
let fruits = ["Apple", "Banana", "Mango"]
console.log(fruits[0]) // Apple at O index
console.log(fruits[1]) // Banana at 1 index
console.log(fruits[2]) // Mango at 2 index
Updating Elements in an Array
let fruits = ["Apple", "Banana", "Mango"]
fruits[1] = "Orange"
console.log(fruits)
//Output: ["Apple", "Banana", "Mango","Orange"]
Array Length Property
Length is the builtin property of Array that provides the number of elements present in Array.
let fruits = ["Apple", "Banana", "Mango", "Orange"]
console.log(fruits.length)
//4
When we want to access any element in array we use loop.
let fruits = ["Apple", "Banana", "Mango"]
for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]) }
Looping Through an Array
When we want to access any element in array we use loop.
let fruits = ["Apple", "Banana", "Mango"]
for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]) }
//output :
//Apple
//Banana
//Mango
Lets Practice this
//Create an array of 5 favorite movies.
let movies = ["Inception", "Avatar", "Titanic", "Joker", "Interstellar"]
//Print First and Last Element
console.log(movies[0])
console.log(movies[4])
//Output
//Inception
//Interstellar
//Change One Value
movies[2] = "Batman"
console.log(movies)
//["Inception", "Avatar", "Batman", "Joker", "Interstellar"]
//Loop Through the Array
for (let i = 0; i < movies.length; i++) {
console.log(movies[i])
}
//Output
//Inception
//Avatar
//Batman
//Joker
//Interstellar
Hope you like how Arrays Worked and make sure you try this!
Thank You!!!
