Selected topic

Arrays

Data Structures

Prefer practical output? Use related tools below while reading.

In JavaScript, an array is a fundamental data structure that stores a collection of values. Think of it as a list or a container that can hold multiple elements.

Key Features of Arrays:


  1. Indexed: Each element in the array has a numerical index (0-based) associated with it.
  2. Ordered: The elements are stored in a specific order, which is determined by their index.
  3. Dynamic size: An array's length can grow or shrink dynamically as elements are added or removed.

Example: Creating an Array


javascript
let colors = ['red', 'green', 'blue'];

In this example, we've created an array called colors with three elements: 'red', 'green', and 'blue'.

Accessing Array Elements


To access an element in the array, you use its index. For example:
javascript
console.log(colors[0]); // Output: "red"

You can also access the last element of the array using the length property:
javascript
console.log(colors[colors.length - 1]); // Output: "blue"

Modifying Array Elements


To modify an element in the array, you assign a new value to its index. For example:
javascript
colors[0] = 'yellow';
console.log(colors); // Output: ["yellow", "green", "blue"]

In this example, we've changed the first element of the colors array from 'red' to 'yellow'.

Adding or Removing Elements


To add an element at the end of the array, you use the push() method:
javascript
colors.push('purple');
console.log(colors); // Output: ["yellow", "green", "blue", "purple"]

To remove an element from the array, you can use the splice() method. For example:
javascript
colors.splice(2, 1);
console.log(colors); // Output: ["yellow", "green", "purple"]

In this example, we've removed the third element ('blue') of the colors array.

Conclusion


Arrays in JavaScript are a powerful and versatile data structure. They allow you to store, access, modify, and manage collections of values with ease. By mastering arrays, you'll be able to write efficient and effective code for a wide range of applications!