JavaScript Arrays
JavaScript Arrays is a core JavaScript concept covering javaScript Arrays: --8<-- "core-logic/data-structures.md" This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
Data Structures: Organizing Information
Data structures are different ways of storing and organizing data so that it can be used efficiently.
Common Types of Data Structures
-
Ordered Collections (Lists/Arrays):
- Items are stored in a specific order.
- Each item has an index (a position number, starting from 0).
- Useful for: A list of names, a sequence of numbers.
-
Unchangeable Collections (Tuples):
- Similar to lists, but once created, they cannot be modified.
- Useful for: Fixed data like GPS coordinates (Latitude, Longitude).
-
Unique Collections (Sets):
- No duplicate items allowed.
- Items are not stored in any specific order.
- Useful for: Tracking unique IDs, removing duplicates.
-
Key-Value Pairs (Maps/Dictionaries):
- Data is stored as a pair: a "Key" (like a label) and its "Value" (the data).
- Useful for: Storing user profiles (Name: "VD", Age: 25).
Choosing the right data structure is 50% of good programming. It makes your code faster and easier to read!
Creating an Array
const cars = ["Saab", "Volvo", "BMW"];
It is a common practice to declare arrays with the const keyword.
Accessing Elements
You access an array element by referring to the index number:
let car = cars[0]; // Saab
Changing an Element
cars[0] = "Opel";
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
However, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements". Objects use names to access its "members".
Array Properties
cars.length // Returns the number of elements
cars.sort() // Sorts the array
Accessing the last element: cars[cars.length - 1].