What is an Array?
An array is a data structure that can hold more than one value at a time. It is a collection of elements, each identified by an index or key. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
Example
In the example above, we created an array named fruits
that stores four elements. We can access each element using its index.
Why Array Indices Start from Zero
In most programming languages, including JavaScript and C++, arrays are zero-indexed. This means the index of the first element is 0, the second element is 1, and so on.
Explanation
The reason for zero-based indexing is rooted in how arrays are managed in memory. When an array is created, the memory address of the first element is the base address. The index of an array element is used as an offset from this base address.
For example, if the base address is 1000
, and each element occupies 4
bytes, the memory address of the first element (index 0
) is 1000 + 0 * 4 = 1000
, the second element (index 1
) is 1000 + 1 * 4 = 1004
, and so on.
Example
In this example, the first element is at index 0
, and subsequent elements are at increasing indices.
Arrays in JavaScript vs. C++
JavaScript arrays are quite different from C++ arrays in several ways:
-
Dynamic Size:
- JavaScript: Arrays in JavaScript are dynamic, meaning they can grow or shrink in size. You can add or remove elements without declaring the size of the array initially.
- C++: In C++, arrays have a fixed size. Once declared, the size cannot be changed. For dynamic arrays, C++ requires you to use pointers and dynamically allocate memory (e.g., using
new
or std::vector
).
-
Heterogeneous Elements:
- JavaScript: Arrays in JavaScript can store elements of different data types (e.g., numbers, strings, objects).
- C++: Arrays in C++ are typically homogeneous, meaning all elements must be of the same data type.
-
Built-in Methods:
- JavaScript: JavaScript arrays come with a wide range of built-in methods such as
push()
, pop()
, map()
, filter()
, and more.
- C++: C++ arrays do not have built-in methods. Instead, you need to use loops or algorithms from the Standard Template Library (STL) to perform operations.
Example in C++
In this C++ example, we declared an array of integers with a fixed size of 4.
Example in JavaScript
In the JavaScript example, the array is dynamic, allowing us to add more elements even after its initial declaration.
Note-
Arrays are a fundamental data structure used in almost every programming language. Understanding how arrays work, especially how indices and memory are handled, is crucial for efficient programming. JavaScript provides a flexible and powerful way to work with arrays, which differs in several ways from how arrays are implemented in languages like C++.