Hi there,

I was trying different types of array initialisation in Javascript and the book that I was reading, said it is possible to initilaise an array with a speicified number of elements in it. However, I tried it and unfortunately, it didn't work. As you can see the code below, the array b should ONLY have 3 empty elements in it. But, that can add more than 3 elements into it.

             var b = new Array(3);

              //assigning values to the indexes of array b
              for(var i=1; i <= 6; i++){
                  b[i]= i;


                  alert(b.length);
                  println(b[i] + ", ");
              }

Dani AI

Generated

Short answer for : new Array(3) does create an array whose length property starts at 3, but JavaScript arrays are resizable — assigning to a numeric index beyond the current highest index increases length and makes sparse slots. That is normal ECMAScript behavior and explains the alerts in the loop. (developer.mozilla.org)

If the goal is simply "don't accidentally grow the array," keep writes guarded instead of relying on the constructor. A small helper is clearer than relying on loop magic and makes intent explicit:

function setAt(arr, index, value) {
  if (!Number.isInteger(index) || index < 0 || index >= arr.length) {
    throw new RangeError('Index out of range');
  }
  arr[index] = value;
}

This follows 's point about using the array's length as the boundary but packages the check so callers get a clear error when they step out of bounds.

If a true fixed-size container is required (no silent growth), use a typed array (Int8Array, Uint8Array, Int32Array, etc.). Typed arrays are fixed-length; writes to numeric indices outside the range do not extend the view and are ignored (they won't change length). This is useful when size must be enforced at the language level rather than by convention. (developer.mozilla.org)

For stricter enforcement (throw on out-of-bounds writes) either make the array non-extensible / make length non-writable (assignments that would add properties then fail — in strict mode they throw) or wrap the array with a Proxy that rejects sets beyond the allowed range. Example Proxy approach:

function fixedArray(len) {
  const target = new Array(len);
  return new Proxy(target, {
    set(t, prop, value, recv) {
      const i = Number(prop);
      if (Number.isInteger(i) && i >= 0 && i >= t.length) {
        throw new RangeError('Index out of bounds');
      }
      return Reflect.set(t, prop, value, recv);
    }
  });
}

Object.preventExtensions() / making length non-writable and Proxy traps are documented behaviors and give different guarantees (silent failure vs thrown error vs custom handling). (developer.mozilla.org)

Recommended Answers

All 5 Replies

When you create the array it does only have 3 elements in it. That doesn't mean you can't add more to it.

JavaScript is not as strict as C# or probably java in terms of initializing an array with a specified number of elements.

I only want it to have three elements in it. Is there a way of doing that? Or Is javascript flexible and not caring so much like Java?

Then make sure that you only loop 3 times :) JavaScript is very flexible and not strict.

I only want it to have three elements in it.

Then put only three elements in it. That doesn't seem very hard to do. If you change your loop to

for(var i=1; i < b.length; i++) {
     b[i]= i;
}

It won't add any additional elements to it. Using b.length as the boundary instead of a magic number is much better code anyway because it's easier to understand and prevents many kinds of mistakes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.