Skip to main content

Command Palette

Search for a command to run...

Javascript arrays 101

Published
3 min read

Imagine you are going grocery shopping. Instead of writing a separate sticky note for every single item you need to buy, one for apples, one for milk, one for bread, you write them all down on a single shopping list. arrays are that shopping list. They are a special type of variable that allows you to store a collection of values in a specific order, all under a single name.

Why Do We Need Arrays?

Imagine you are building a simple app to track your top three favorite fruits. Without arrays, you would have to store each fruit in its own separate variable.

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

// with array
let fruitArray = ["apple", "banana", "mango"]

How to Create an Array

Creating an array in JavaScript is incredibly straightforward. You use square brackets [] and separate your items with commas.

//  array of strings
let tasks = ["Wake up", "Drink water", "Learn JavaScript"];

// array of numbers
let testScores = [85, 92, 78, 99];

Accessing Elements Using the Index

How do you get a specific item out of your array? You use its index. The most important rule to remember about arrays is that counting starts at 0, not 1. This is known as zero-based indexing.

If we look at our fruits array:

  • "Apple" is at index 0

  • "Banana" is at index 1

  • "Mango" is at index 2

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

console.log(fruits[0]); 
console.log(fruits[2]); 

Updating Elements

Arrays are flexible. You can easily change the value of an element after the array has been created by selecting its index and assigning a new value. Let's say we want to replace "Banana" with "Orange"

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


fruits[1] = "Orange";

console.log(fruits); 

Basic Looping Over Arrays

If you want to print every item in your array, we can use a basic for loop to loop over the array.

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

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

/* Output:
I love eating Apple
I love eating Orange
I love eating Mango
*/

Lets dry run it once -

  1. let i = 0: We start our counter (i) at 0, which perfectly matches our array's first index.

  2. i < fruits.length: The loop keeps running as long as i is less than the total number of items (3).

  3. i++: After each loop, i increases by 1, allowing us to move to the next item in the array.