Create and Manipulate Arrays in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

Introduction

In this lab, students will explore the fundamental concepts of creating and manipulating arrays in JavaScript. The lab provides a comprehensive introduction to array initialization, accessing array elements, and performing basic array operations through practical coding exercises. Participants will learn how to create arrays using different methods, including square bracket notation and the Array constructor, and understand how to work with arrays containing various data types.

The lab covers key skills such as defining arrays with numbers, strings, and mixed elements, accessing individual array elements using indexes, and demonstrating basic array manipulation techniques. By working through hands-on examples, learners will gain practical experience in creating, accessing, and interacting with arrays, which are essential data structures in JavaScript programming.

Understand Array Definition and Initialization

In this step, you'll learn about arrays in JavaScript, which are fundamental data structures used to store multiple values in a single variable. Arrays allow you to collect and organize related data efficiently.

Let's start by creating a simple array in JavaScript. Open the WebIDE and create a new file called arrays.js in the ~/project directory.

// Creating an array of numbers
let numbers = [1, 2, 3, 4, 5];

// Creating an array of strings
let fruits = ["apple", "banana", "orange"];

// Creating an empty array
let emptyArray = [];

// Creating an array with mixed data types
let mixedArray = [42, "hello", true, null];

console.log("Numbers array:", numbers);
console.log("Fruits array:", fruits);
console.log("Empty array:", emptyArray);
console.log("Mixed array:", mixedArray);

When you run this code, you'll see the following example output:

Numbers array: [1, 2, 3, 4, 5]
Fruits array: ['apple', 'banana', 'orange']
Empty array: []
Mixed array: [42, 'hello', true, null]

Key points about array initialization:

  • Arrays are created using square brackets []
  • Arrays can contain elements of different types
  • Arrays can be empty or pre-populated
  • The first element of an array is always at index 0

You can also create arrays using the Array constructor:

// Using Array constructor
let numbersConstructor = new Array(1, 2, 3, 4, 5);
console.log("Array using constructor:", numbersConstructor);

Access Array Elements Using Indexes

In this step, you'll learn how to access individual elements in an array using their index. In JavaScript, array indexes start at 0, which means the first element is at index 0, the second at index 1, and so on.

Open the arrays.js file in the ~/project directory and add the following code:

// Create an array of colors
let colors = ["red", "green", "blue", "yellow", "purple"];

// Accessing array elements by index
console.log("First color:", colors[0]); // First element
console.log("Third color:", colors[2]); // Third element
console.log("Last color:", colors[colors.length - 1]); // Last element

// Modifying array elements
colors[1] = "orange"; // Change the second element
console.log("Modified colors array:", colors);

// Demonstrating index range
console.log("Array length:", colors.length);

When you run this code, you'll see the following example output:

First color: red
Third color: blue
Last color: purple
Modified colors array: ['red', 'orange', 'blue', 'yellow', 'purple']
Array length: 5

Key points about array indexing:

  • Indexes start at 0
  • Use square brackets [] to access elements
  • array.length gives the total number of elements
  • You can modify elements by assigning a new value to a specific index
  • To access the last element, use array[array.length - 1]

Try accessing elements outside the array's range to see what happens:

console.log("Accessing out-of-range index:", colors[10]); // Returns undefined

Create an Array of Fruits

In this step, you'll create an array of fruits and learn how to work with it. Open the arrays.js file in the ~/project directory and add the following code:

// Create an array of fruits
let fruits = ["apple", "banana", "orange", "mango", "strawberry"];

// Display the entire fruits array
console.log("Fruits array:", fruits);

// Add a new fruit to the end of the array
fruits.push("grape");
console.log("Fruits after adding grape:", fruits);

// Create an array with different types of fruits
let tropicalFruits = ["pineapple", "coconut", "papaya"];

// Combine two fruit arrays
let allFruits = fruits.concat(tropicalFruits);
console.log("All fruits:", allFruits);

// Check the number of fruits
console.log("Total number of fruits:", allFruits.length);

When you run this code, you'll see the following example output:

Fruits array: ['apple', 'banana', 'orange', 'mango', 'strawberry']
Fruits after adding grape: ['apple', 'banana', 'orange', 'mango', 'strawberry', 'grape']
All fruits: ['apple', 'banana', 'orange', 'mango', 'strawberry', 'grape', 'pineapple', 'coconut', 'papaya']
Total number of fruits: 9

Key points about creating and manipulating fruit arrays:

  • Arrays can be created with multiple elements
  • You can add new elements using push()
  • Arrays can be combined using concat()
  • length property shows the total number of elements

Print Array Elements to Web Page

In this step, you'll learn how to display array elements on a web page using HTML and JavaScript. First, create an HTML file called fruits.html in the ~/project directory:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Fruits Array Display</title>
    <style>
      body {
        font-family: Arial, sans-serif;
      }
      #fruits-list {
        background-color: #f4f4f4;
        padding: 20px;
        border-radius: 5px;
      }
    </style>
  </head>
  <body>
    <h1>My Fruits Collection</h1>
    <div id="fruits-list"></div>

    <script>
      // Create an array of fruits
      let fruits = ["Apple", "Banana", "Orange", "Mango", "Strawberry"];

      // Get the fruits list container
      let fruitsList = document.getElementById("fruits-list");

      // Create an unordered list to display fruits
      let ul = document.createElement("ul");

      // Loop through the fruits array and create list items
      fruits.forEach(function (fruit) {
        let li = document.createElement("li");
        li.textContent = fruit;
        ul.appendChild(li);
      });

      // Add the list to the page
      fruitsList.appendChild(ul);
    </script>
  </body>
</html>

This example demonstrates several key concepts:

  • Creating an HTML structure
  • Using JavaScript to manipulate the DOM
  • Displaying array elements on a web page
  • Using forEach() to iterate through array elements

When you open this HTML file in a web browser, you'll see a list of fruits displayed on the page.

Alternative method using innerHTML:

// Alternative method to display fruits
let fruitsList = document.getElementById("fruits-list");
fruitsList.innerHTML = fruits.map((fruit) => `<li>${fruit}</li>`).join("");

Explore Basic Array Operations

In this step, you'll learn about common array operations in JavaScript. Open the arrays.js file in the ~/project directory and add the following code:

// Create an array of numbers
let numbers = [5, 2, 8, 1, 9, 3];

// Adding elements
numbers.push(10); // Add element to the end
numbers.unshift(0); // Add element to the beginning
console.log("After adding elements:", numbers);

// Removing elements
let lastNumber = numbers.pop(); // Remove last element
let firstNumber = numbers.shift(); // Remove first element
console.log("After removing elements:", numbers);

// Sorting the array
numbers.sort((a, b) => a - b); // Ascending order
console.log("Sorted array:", numbers);

// Reversing the array
numbers.reverse();
console.log("Reversed array:", numbers);

// Finding elements
let index = numbers.indexOf(8);
console.log("Index of 8:", index);

// Slicing the array
let slicedNumbers = numbers.slice(1, 4);
console.log("Sliced array:", slicedNumbers);

// Filtering the array
let evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log("Even numbers:", evenNumbers);

// Mapping the array
let squaredNumbers = numbers.map((num) => num * num);
console.log("Squared numbers:", squaredNumbers);

When you run this code, you'll see the following example output:

After adding elements: [0, 5, 2, 8, 1, 9, 3, 10]
After removing elements: [5, 2, 8, 1, 9, 3, 10]
Sorted array: [1, 2, 3, 5, 8, 9, 10]
Reversed array: [10, 9, 8, 5, 3, 2, 1]
Index of 8: 2
Sliced array: [9, 8, 5]
Even numbers: [10, 8, 2]
Squared numbers: [100, 81, 64, 25, 9, 4, 1]

Key array operations demonstrated:

  • push() and unshift() to add elements
  • pop() and shift() to remove elements
  • sort() to order elements
  • reverse() to flip array order
  • indexOf() to find element position
  • slice() to extract a portion of an array
  • filter() to create a new array with specific elements
  • map() to transform array elements

Summary

In this lab, participants explored the fundamentals of working with arrays in JavaScript, learning how to create, initialize, and manipulate array data structures. The lab covered key concepts such as defining arrays using square brackets and the Array constructor, demonstrating the ability to create arrays with different types of elements, including numbers, strings, and mixed data types.

Participants gained practical skills in accessing array elements through indexing, understanding that array indexes start at 0, and learned how to perform basic array operations. The hands-on approach allowed learners to practice creating arrays, logging their contents, and exploring the flexibility of JavaScript arrays in storing and organizing data efficiently.

Other JavaScript Tutorials you may like