Lesson 1: What Are Arrays?

Lesson Goal:

To understand what arrays are in JavaScript, why we use them, and how to define and access their elements.


What is an Array?

An array is a special variable that can hold multiple values at once. Instead of creating separate variables for each item, you can store them all in a single array.

Real-World Analogy:

Think of an array like a shopping list — a single container holding several related items:

let shoppingList = ["milk", "bread", "eggs", "butter"];

Array Syntax:

let fruits = ["apple", "banana", "cherry"];
  • Square brackets [] define the array
  • Values are separated by commas
  • Each value is called an element
  • Elements can be strings, numbers, booleans, objects, or even other arrays

Indexing in Arrays

Each element in an array has a position number, called an index, starting from 0.

IndexValue
0“apple”
1“banana”
2“cherry”

You can access array items like this:

console.log(fruits[0]);  // Output: apple
console.log(fruits[2]);  // Output: cherry

Why Use Arrays?

  • Store multiple related values together
  • Make data easier to organize and process
  • Useful for loops, data structures, and UI rendering

Example Use Cases:

  • List of products in a shopping cart
  • Usernames in a chat app
  • Scores in a game

Fun Fact:

Arrays can hold mixed data types, although it’s better to keep elements consistent:

let mixed = ["hello", 42, true, null];

Try It Yourself:

let colors = ["red", "green", "blue"];
console.log("First color:", colors[0]);
console.log("Third color:", colors[2]);