Skip to content

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ΒΆ

  1. 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.
  2. Unchangeable Collections (Tuples):

    • Similar to lists, but once created, they cannot be modified.
    • Useful for: Fixed data like GPS coordinates (Latitude, Longitude).
  3. Unique Collections (Sets):

    • No duplicate items allowed.
    • Items are not stored in any specific order.
    • Useful for: Tracking unique IDs, removing duplicates.
  4. 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ΒΆ

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

Last Element

Accessing the last element: cars[cars.length - 1].