HTML provides several collection data types that allow you to store and manipulate groups of related data. These collection data types include arrays, sets, and maps. Let’s take a closer look at each of these types and understand how they are defined.
Arrays
An array is a collection that stores multiple values in a single variable. The values in an array are stored in a specific order, and each value can be accessed using its index. Arrays are defined using the Array object in JavaScript.
To define an array, you can use the array literal syntax by enclosing the values within square brackets ([]). For example:
var fruits = ["apple", "banana", "orange"];
In this example, we have defined an array called fruits, which contains three elements: “apple”, “banana”, and “orange”. The index of the elements starts from 0, so fruits[0] will give us “apple”.
Sets
A set is a collection of unique values where each value occurs only once. Sets are not ordered, meaning the values are not stored in any particular sequence. Sets are defined using the Set object in JavaScript.
To define a set, you can use the set literal syntax by enclosing the values within curly brackets ({}) or by passing an iterable (like an array) to the Set constructor. For example:
// Using set literal syntax var colors = new Set(["red", "green", "blue"]); // Using Set constructor with iterable var numbers = new Set([1, 2, 3]);
In this example, we have defined two sets: colors and numbers. The set colors contains the values “red”, “green”, and “blue”, while the set numbers contains the values 1, 2, and 3.
Maps
A map is a collection of key-value pairs where each key is unique. Maps are similar to objects, but unlike objects, maps allow any value as a key. Maps are defined using the Map object in JavaScript.
To define a map, you can use the map literal syntax by enclosing the key-value pairs within curly brackets ({}) or by passing an iterable (like an array) of arrays to the Map constructor. For example:
// Using map literal syntax var user = new Map([["name", "John"], ["age", 25]]); // Using Map constructor with iterable var city = new Map([["name", "New York"], ["population", 8.4 million]]);
In this example, we have defined two maps: user and city. The map user contains the key-value pairs “name”-“John” and “age”-25, while the map city contains the key-value pairs “name”-“New York” and “population”-8.4 million.
In conclusion,
We have explored three collection data types in HTML: arrays, sets, and maps. Arrays store multiple values in a specific order, sets store unique values without any specific order, and maps store key-value pairs with unique keys. Understanding these collection data types is essential for effective data manipulation in JavaScript.