JavaScript Arrays - Creating and Manipulating Lists
Arrays are versatile data structures in JavaScript used to store collections of items. In this guide, we'll explore how to create and manipulate lists using JavaScript arrays.
Creating Arrays
You can create an array in JavaScript using square brackets []
and adding items separated by commas:
// Creating an array of numbers
let numbers = [1, 2, 3, 4, 5];
// Creating an array of strings
let fruits = ["apple", "banana", "cherry"];
// Creating an empty array
let emptyArray = [];
Accessing Array Elements
You can access array elements by their index, starting from 0 for the first element:
console.log(numbers[0]); // Outputs: 1
console.log(fruits[1]); // Outputs: "banana"
Array Methods
JavaScript arrays come with built-in methods for manipulation:
// Adding elements to an array
fruits.push("date"); // Adds "date" to the end
fruits.unshift("apricot"); // Adds "apricot" to the beginning
// Removing elements from an array
fruits.pop(); // Removes the last element ("date")
fruits.shift(); // Removes the first element ("apricot")
// Finding elements in an array
let index = fruits.indexOf("banana"); // Returns the index of "banana"
Iterating Over Arrays
You can loop through arrays using various methods such as for
loops, forEach
, and more:
// Using a for loop
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// Using forEach
fruits.forEach(function (fruit) {
console.log(fruit);
});
Modifying Array Elements
You can modify array elements by assigning new values to them:
numbers[2] = 100; // Changes the third element to 100
fruits[1] = "grape"; // Changes the second element to "grape"
Conclusion
JavaScript arrays are powerful tools for handling lists of data. Whether you need to store numbers, strings, or more complex objects, arrays provide a flexible and convenient way to work with collections. Understanding how to create and manipulate arrays is essential for JavaScript development.
Happy coding!