javascript
  1. javascript-array

JavaScript Array

Syntax

An array is a type of data structure in JavaScript that can store a collection of values, such as numbers, strings, or other objects. In JavaScript, an array is defined using square brackets, and each element in the array is separated by a comma.

var myArray = [element1, element2, element3, ..., elementN];

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Array Example</title>
</head>
<body>

<!-- Placeholder for displaying the output -->
<p id="output"></p>

<script>
    // Define an array
    var myArray = ['apple', 'banana', 'orange'];

    // Access and display the first element
    var firstElement = myArray[0];
    document.getElementById("output").innerHTML += "First Element: " + firstElement + "<br>";

    // Display the length of the array
    document.getElementById("output").innerHTML += "Array Length: " + myArray.length + "<br>";

    // Add 'grape' to the end of the array
    myArray.push('grape');

    // Display the modified array
    document.getElementById("output").innerHTML += "Modified Array: " + JSON.stringify(myArray);
</script>

</body>
</html>
Try Playground

Output

The output will depend on the specific example used, but in general, an array can be used to store and manipulate collections of data in JavaScript.

Explanation

Arrays in JavaScript are essentially a way to store multiple values in a single variable. Each element in the array is accessed using its index, starting at 0 for the first element. Arrays also have properties and methods that can be used to manipulate the data stored within them.

In the example above, we define an array of fruits, with the elements 'apple', 'banana', and 'orange'. We then use the console.log() function to output the first element of the array ('apple'), the length of the array (3), and the array itself after adding a new element ('grape') using the push() method.

Use

Arrays are commonly used in JavaScript to store lists of data, such as user input, responses from APIs, or options for a drop-down menu. They are also used in loops and other programming constructs to iterate over collections of data.

Important Points

  • Arrays in JavaScript are defined using square brackets, with each element separated by a comma.
  • The index of the first element in an array is 0.
  • Arrays can store any type of value, including numbers, strings, objects, and other arrays.
  • Arrays have built-in properties and methods, such as length and push(), that can be used to manipulate the data stored within them.

Summary

JavaScript arrays are a powerful data structure that can be used to store collections of data in a single variable. With built-in properties and methods, and the ability to store any type of value, arrays are a versatile tool for developers to use in their programs.

Published on: