In this lesson, you will learn how to create arrays and add or remove items in JavaScript. By the end, you will be able to manage a list of items effectively. This skill is essential for organizing data in your programs.
An array is a way to store multiple values in a single variable. For example, if you want to remember the names of your friends, you can store them in an array. Thus, arrays help in grouping related data together, making it easier to work with.
To create an array, you use square brackets. Here’s an example:
File: arrays.php
$friends = ["Alice", "Bob", "Charlie"];
You can add items to an existing array using the push() method. This method adds one or more elements to the end of the array. Here is how you do it:
$friends[] = "David"; // Adding "David" to the array
print_r($friends); // Displays the current array
To remove an item, use the array_splice() function. This function can remove a specific number of elements from an array. Here’s an example:
array_splice($friends, 1, 1); // Removes "Bob"
print_r($friends); // Displays the array after removal
The initial line creates an array of friends. When we add “David”, the array now includes all four names. The array_splice() function removes the second item, which is “Bob”, from the array. Therefore, understanding these functions allows you to manipulate arrays effectively.
Now, create an array with your favorite movies. First, use push() to add another movie, and next, use array_splice() to remove one movie from the list. This task will help you practice and reinforce what you’ve learned.
$movies = ["Inception", "Avatar", "Titanic"];
$movies[] = "The Matrix"; // Add "The Matrix"
array_splice($movies, 1, 1); // Remove "Avatar"
print_r($movies); // Displays the movies array
push() to add elements and array_splice() to remove them.push() method.array_splice(), noting the index starting from 0.Additionally, if you want to enhance your JavaScript knowledge, check out our lesson on JavaScript basics for further insights.
For more foundational information on JavaScript, you may also want to visit this lesson on how JavaScript works with HTML and CSS.