EasyCode365EasyCode365

Arrays

Imagine you are writing a grocery list or keeping track of high scores in a game.

Instead of writing each item in a separate variable, you can group related values into one list. In JavaScript, that list is called an array.

What an array is

An array is a special container that holds multiple values inside a single variable.

Instead of storing only one piece of information, like one number or one word, an array can store a list of related values in one place.

Why arrays are useful

Imagine you want to store your favorite colors.

You could create separate variables like color1, color2, and color3. That might work for three colors, but it becomes messy if you need to store many more.

Arrays keep related data organized under one variable name.

First code example

Here is how you create a simple array in JavaScript.

Can edit
const favoriteFoods = ["pizza", "tacos", "sushi", "burgers"];

console.log(favoriteFoods);

Code walkthrough

Let's break down how we built the list above:

  • Arrays use square brackets [].
  • Each item inside the array is separated by a comma.
  • The full list is stored in one variable named favoriteFoods.
  • console.log(favoriteFoods) sends the full array to the Output section after you click Run.

Reading one item from an array

Often, you do not need the whole list at once. You may want to read one specific item.

Every item in an array has a numbered position called an index.

JavaScript array indexes start at 0. That means:

  • The first item is at index 0.
  • The second item is at index 1.
  • The third item is at index 2.

To read one item, write the array name followed by square brackets with the index number.

Can edit
const colors = ["red", "blue", "green"];

console.log(colors[0]); // This prints "red"

You can find out how many items are in an array with .length.

Can edit
const colors = ["red", "blue", "green"];

console.log(colors.length);

This sends 3 to the Output section because the array has three items.

Mini task

Look at the colors code block above.

Change the index number inside console.log(colors[0]) so it prints "blue" in the Output section.

Short quiz

Question: If you have an array of top scores, what index number would you use to access the fourth score in the list?

Answer: You would use index 3.

Because array indexes start at 0, the fourth item is at index 3.

Small challenge

Create an array that holds three of your favorite numbers.

Then use console.log() to read and print only the second number from your array.

Can edit
// put your code below

console.log()

Summary

Array with index and legth

  • An array is a list of multiple values stored in one variable.
  • Arrays use square brackets [].
  • Items inside an array are separated by commas.
  • Array indexes start at 0.
  • .length tells you how many items are inside an array.