Space complexity for array[] vs object{} in JavaScript?

I’m learning to analyze space complexity, but I’m confused of analyzing an array vs an object in JS. So I’d like to get some help here.

ex1. array

let table = [];
for (let i = 0; i < 26; i++) {
    table[s.charAt(i) - 'a']++;

ex1. is from an example online, and it says the space complexity is O(1) because the table’s size stays constant.

ex2. object {}

let nums[0,1,2,3,4,5], map = {};
for (let i = 0; i < nums.length; i++) {
   map[ nums[i] ] = i;

I think ex2. uses O(n) because the map object is accessed 6 times. However, if I use the concept learned from ex1., the space complexity should be O(1)? Any ideas where I went wrong?

The first example is not JavaScript.

An array is an object in JS, you’re trying to compare two different languages as @Sky020 says.

Space complexity isn’t something you should care about in JavaScript. If you have objects or arrays of sizes that potentially could cause memory issues, then you’ve most likely chosen wrong language.

But in general, you’re correct. If you initialize an array of fixed size and then fill those slots you do not increase memory. And when you initialize new empty map or object and then put stuff in it - memory usage grows.

1 Like