1

I was taught that, in JavaScript, if I define an array's size I should also fill it.

Why is that the case? I read a blog article years ago about a series of specific steps to break the size of empty arrays but I cannot find it today.

// bad
Array(100)

// good
Array(100).fill(0)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user3456978
  • 238
  • 1
  • 13
  • 6
    There are some methods like `.map()` that ignore uninitialized elements, which can cause confusing results. – Barmar Jun 26 '23 at 21:30
  • 2
    In short, without initializing an array created this way, all elements are `undefined`. This is generally undesirable and may cause some runtime issues if you later reference an uninitialized element in the array. Note that if you do initialize the array by some other means before the elements are referenced, then you don't necessarily need the `.fill(0)` part. In fact, `.fill(0)` is probably a bad idea if you are not intending the Array to store number types. – h0r53 Jun 26 '23 at 21:43
  • 3
    Why do you even define an array's size (if you don't intend to fill it)? – Bergi Jun 26 '23 at 21:56
  • The origination of this question was more of a thought exercise about how things work. I could see someone who isn't primarily a javascript dev defining an array of fixed length and putting in data they have now with the intention of putting in the rest when it's available. Or Dave Newton's explanation in the answer below. – user3456978 Jun 27 '23 at 02:40

1 Answers1

0

I searched and came to this conclusion:

In JavaScript, when you define an array of a given size using "Array()" without filling it, memory is allocated for the array, but the elements within the array are left with no initial value. This means that the array has reserved memory space for a certain number of elements, but those elements are not assigned any specific value. For example, when you code "Array(100)", JavaScript sets aside memory for possible future values, but that remains unused until you explicitly assign values to the array elements.

So every element in the array consumes memory, even if no meaningful value is assigned to it.

Also, by initializing the array with specific values, unexpected behavior is avoided when accessing or iterating over the array.


I hope my explanation has been useful.

Shahnazi2002
  • 43
  • 1
  • 8
  • 1
    Having a chunk of memory without (necessarily) useful values isn’t intrinsically bad, e.g., we might allocate a fixed-size array for a circular buffer before needing it to contain values. – Dave Newton Jun 26 '23 at 23:24
  • 1
    Sorry, your conclusion is incorrect. Memory is not reserved for each element at time of creating the array. See https://stackoverflow.com/a/20323491/634824 – Matt Johnson-Pint Jun 26 '23 at 23:29