JavaScript ArraysΒΆ
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).
Which one to use?
Choosing the right data structure is 50% of good programming. It makes your code faster and easier to read!
Creating an ArrayΒΆ
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:
Changing an ElementΒΆ
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ΒΆ
Last Element
Accessing the last element: cars[cars.length - 1].