Array Usage

Tutorial 2 of 4

1. Introduction

In this tutorial, we're going to learn about one of the most important data structures in programming: arrays. Arrays can be thought of as a list that can hold multiple values under a single name. This makes them incredibly useful for storing and operating on sets of data. By the end of this tutorial, you will understand how to declare, initialize, and manipulate arrays.

Prerequisites: A basic understanding of programming concepts and HTML.

2. Step-by-Step Guide

Arrays can store multiple values in a single variable, which can be accessed by a numerical index. The index of an array starts from 0.

Here's how you create an array:

var myArray = ["apple", "banana", "cherry"];

In this example, "apple", "banana", and "cherry" are elements of the array. You can access these elements via their index. For instance, myArray[0] would give you "apple".

Best Practices and Tips

  • It's good practice to keep all elements in an array of the same data type.
  • Always remember that JavaScript array indexes start from 0, not 1.
  • Use descriptive names for your arrays to make your code easier to read and maintain.

3. Code Examples

Here are some practical examples of array usage:

Example 1: Accessing Array Elements

var myArray = ["apple", "banana", "cherry"];
document.write(myArray[1]); // Outputs "banana"

Example 2: Modifying Array Elements

var myArray = ["apple", "banana", "cherry"];
myArray[1] = "blackberry"; // Change "banana" to "blackberry"
document.write(myArray[1]); // Outputs "blackberry"

Example 3: Finding the Length of an Array

var myArray = ["apple", "banana", "cherry"];
document.write(myArray.length); // Outputs 3

4. Summary

In this tutorial, we've learned how to declare, initialize, and manipulate arrays. We've also looked at how to access and modify array elements, and how to find the length of an array.

For further learning, you should look into multidimensional arrays, as well as different array methods like push, pop, shift, unshift, and others.

5. Practice Exercises

Exercise 1: Create an array that stores the names of five countries, then output the third country in your array.

Exercise 2: Create an array that stores five numbers. Change the fourth number to 100.

Exercise 3: Create an array that stores any three values. Output the length of the array.

Solutions:

Exercise 1:

var countries = ["USA", "Canada", "Germany", "France", "China"];
document.write(countries[2]); // Outputs "Germany"

Exercise 2:

var numbers = [5, 10, 15, 20, 25];
numbers[3] = 100; // Change the fourth number to 100
document.write(numbers[3]); // Outputs 100

Exercise 3:

var myArray = ["Hello", 42, true];
document.write(myArray.length); // Outputs 3