JavaScript Arrays
In JavaScript, an array is a data structure used to store multiple values in a single variable. Arrays are ordered collections, where each value (or element) has a numeric index, starting from zero. Arrays provide various built-in methods to work with and manipulate data efficiently.
Key Features of JavaScript Arrays:
- Indexed Elements: Each element in an array is accessed using its index, starting from 0.
- Dynamic Size: JavaScript arrays can grow or shrink dynamically, allowing you to add or remove elements as needed.
- Built-in Methods: Arrays come with many useful methods for sorting, filtering, transforming, and iterating over elements.
Example of Creating a JavaScript Array:
This example demonstrates how to create a basic array and access its elements:
Example
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits[2]); // Cherry
Output
Banana
Cherry
Adding and Removing Elements:
You can add elements to an array using the push()
and unshift()
methods, and remove elements using the pop()
and shift()
methods:
Example
const numbers = [1, 2, 3];
numbers.push(4); // Adds 4 to the end
numbers.unshift(0); // Adds 0 to the beginning
numbers.pop(); // Removes the last element
numbers.shift(); // Removes the first element
console.log(numbers); // [2, 3]
Output
Array Methods for Transformation:
JavaScript provides various methods to transform arrays. Here’s an example of using the map()
and filter()
methods:
Example
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const even = numbers.filter(n => n % 2 === 0);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(even); // [2, 4]
Output
[2, 4]
When to Use JavaScript Arrays:
Arrays are ideal for storing and manipulating lists of items, such as user data, names, or numbers. They are widely used for organizing data that requires frequent access and transformation. Arrays are essential in managing collections of data in JavaScript applications.