arrays

In this module we'll study arrays.

Location Check

Let's get you where you gotta be:

            └── 3-JavaScript-Basics
                08-arrays.js       <----You should be working here.

Description

An array is a numerically indexed map of values. Starting out, it's easier to just say it's a great way to collect a bunch of values together. They allow us to collect things like names, usernames, product names, prices, etc.

Sample Code

Add these arrays to the file:

var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
var raceWinners = [33, 72, 64];
var myFavoriteThings = ['Broccoli', 46074, 'Zombie Cats From Mars'];

Take a minute and think about this:

Read the above examples, what do you think are some general rules about arrays?

Key Points

Here are some key points:

  • An array is created like a variable.

  • It can be named anything.

  • We use square brackets [] to collect values.

  • We separate items with commas in the brackets.

  • We can have a collection of one type(6 strings that are zombie movies).

  • We can also collect multiple types:

var mySecretSpyInfo = ["James Bond", 007, true];

The 0 index

An important fact that everybody learns when they first start coding:

The index of an array starts at 0

Check it out:

                    //0        1        2
var countryArray = ["USA", "Russia", "China"];

Access Values

You can access arrays using bracket notation []. Print some of these array values by naming the array and then naming the index position:

console.log(countryArray[2]);  //what will print here?
console.log("Country Array:", countryArray[0]); //And here?

More Practice

Write four different arrays that have 4 values. Print four of the values in console statements. Try this:

  • Print the first value of the first array. Remember 0!

  • Print the second value of the second array.

  • Print the third value of the third array.

  • Print the fourth value of the fourth array.

If you can't get that, just create some arrays and print what you can. Just play around and figure out what you can. There are also some great ways to go learn online. Just Google it.

Last updated