Array length property in Javascript - Time & Space Complexity
We want to understand how fast we can get the size of an array using its length property.
How does the time to find the length change as the array grows?
Analyze the time complexity of the following code snippet.
const arr = [1, 2, 3, 4, 5];
const size = arr.length;
console.log(size);
This code gets the length of an array and prints it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the
lengthproperty of the array. - How many times: Exactly once, no loops or repeated steps.
Getting the length does not depend on how big the array is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation count stays the same no matter the array size.
Time Complexity: O(1)
This means getting the array length takes the same small amount of time no matter how big the array is.
[X] Wrong: "Getting the length takes longer if the array is bigger because it counts all items each time."
[OK] Correct: The length is stored as a property, so it is instantly available without counting.
Knowing that array length access is very fast helps you write efficient code and answer questions confidently.
"What if we loop through the array to count items instead of using length? How would the time complexity change?"