Skip to main content

Command Palette

Search for a command to run...

JavaScript Arrays 101

Updated
โ€ข3 min read
JavaScript Arrays 101

๐Ÿ“Œ What Are Arrays and Why Do We Need Them?

Imagine you want to store:

๐ŸŽ Apple
๐ŸŒ Banana
๐Ÿฅญ Mango
๐Ÿ‡ Grapes

If you store them separately:

let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Mango";
let fruit4 = "Grapes";

This becomes messy.

Instead, we use an array:

let fruits = ["Apple", "Banana", "Mango", "Grapes"];

๐Ÿ‘‰ An array is a collection of values stored in order.


๐Ÿ“ฆ Why Arrays Are Needed

โœ” Store multiple values in one variable

โœ” Easy to manage lists

โœ” Easy to loop through

โœ” Used everywhere (APIs, databases, projects)


๐Ÿ“Œ How to Create an Array

let numbers = [10, 20, 30, 40];

Structure:

let arrayName = [value1, value2, value3];

๐Ÿ”ข Accessing Elements Using Index

Arrays use index numbers.

โš  Important: Index starts from 0

let fruits = ["Apple", "Banana", "Mango"];
Index Value
0 Apple
1 Banana
2 Mango

Example

console.log(fruits[0]);  // Apple
console.log(fruits[2]);  // Mango

๐Ÿ”„ Updating Elements

You can change values using index.

fruits[1] = "Orange";
console.log(fruits);

Before:

["Apple", "Banana", "Mango"]

After:

["Apple", "Orange", "Mango"]

๐Ÿ“ Array Length Property

To check how many elements:

console.log(fruits.length);

Output:

3

Length is very useful in loops.


๐Ÿ” Basic Looping Over Arrays

Using for loop

let fruits = ["Apple", "Banana", "Mango"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Output:

Apple
Banana
Mango

This loop:

  1. Starts from index 0

  2. Continues until length

  3. Prints each value


๐Ÿ†š Individual Variables vs Array

โŒ Without Array

let mark1 = 80;
let mark2 = 75;
let mark3 = 90;

Hard to manage.


โœ… With Array

let marks = [80, 75, 90];

Clean and organized.


๐ŸŽ“ Assignment Practice

1๏ธโƒฃ Create an Array of 5 Favorite Movies

let movies = ["Inception", "Interstellar", "KGF", "3 Idiots", "Avengers"];

2๏ธโƒฃ Print First and Last Element

console.log(movies[0]);  // First
console.log(movies[movies.length - 1]);  // Last

3๏ธโƒฃ Change One Value

movies[2] = "Bahubali";
console.log(movies);

4๏ธโƒฃ Loop Through the Array

for (let i = 0; i < movies.length; i++) {
  console.log(movies[i]);
}

๐Ÿ“Š Diagram Ideas

๐Ÿ”น Visual Representation of Array Index

Index:   0        1        2        3
         --------------------------------
Value: | Apple | Banana | Mango | Grapes |
         --------------------------------

๐Ÿ”น Memory-Style Block Diagram

fruits
   โ†“
[0] โ†’ Apple
[1] โ†’ Banana
[2] โ†’ Mango
[3] โ†’ Grapes

๐ŸŒŸ Final Understanding

  • Array = ordered collection of values

  • Index starts from 0

  • Access using array[index]

  • Can update values

  • length gives total elements

  • Use loops to print all elements