JavaScript Arrays

Arrays in JavaScript are used to store multiple values in a single variable. They maintain an ordered collection and provide methods to add, remove, and manipulate elements efficiently.

Key Topics

Defining Arrays

Arrays can be defined using square brackets. Elements can be of any data type, including numbers, strings, or objects.

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits);

Output

> ["Apple", "Banana", "Cherry"]

Explanation: The fruits array stores three string elements. Logging it displays the entire array and its elements.

Accessing Elements

Array elements are accessed by their index, starting at 0. Using an index returns the element at that position.

console.log(fruits[0]);
console.log(fruits[1]);

Output

> Apple

> Banana

Explanation: fruits[0] returns "Apple", and fruits[1] returns "Banana" based on their positions in the array.

Array Length

The .length property returns the number of elements in an array.

console.log(fruits.length);

Output

> 3

Explanation: The length property of fruits is 3, reflecting the total elements in the array.

JavaScript Usage in DOM

This DOM-based example demonstrates using an array to store items and display them dynamically on the webpage.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arrays in DOM</title>
</head>
<body>
    <h1>Array Demo</h1>
    <button onclick="showFruits()">Show Fruits</button>
    <p id="display"></p>

    <script>
        function showFruits() {
            let fruits = ["Apple", "Banana", "Cherry"];
            document.getElementById("display").textContent = fruits.join(", ");
        }
    </script>
</body>
</html>

Key Takeaways

  • Definition: Arrays store multiple values in an ordered list.
  • Access: Use indices to retrieve elements.
  • Length: The length property gives the number of elements.
  • DOM Integration: Dynamically display array contents on webpages.