DT.COM.05 array

An array is a data structure for storing elements of the same type, accessible by indices. Arrays can be fixed-size or dynamically resizable.

Array Example

Arrays provide a method to store multiple values into a single variable, simplifying data management and accessibility. Here's an example to demonstrate their usage:

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

This snippet creates an array named fruits, containing three string elements. To access an element, you use its index (starting from 0), as shown with "Apple".

Array Key-Value Pairs

While arrays traditionally use numeric indices for accessing elements, you can leverage them to represent key-value pairs. This approach provides a way to associate data with a unique identifier, similar to objects.


let fruitData = [];
fruitData["apple"] = "red";
fruitData["banana"] = "yellow";
fruitData["cherry"] = "red";
console.log(fruitData["apple"]); // Outputs: red

Last updated