mrdoob/three.js · error

THREE.Vector3: index is out of range: ${index}

Error message

THREE.Vector3: index is out of range: ${index}

What it means

Thrown by Vector3.setComponent(index, value) when index is not 0, 1, or 2. setComponent maps 0->x, 1->y, 2->z; a Vector3 has exactly three components, so indices 3 and above (or negatives) are out of range.

Source

Thrown at src/math/Vector3.js:168

		return this;

	}

	/**
	 * Allows to set a vector component with an index.
	 *
	 * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
	 * @param {number} value - The value to set.
	 * @return {Vector3} A reference to this vector.
	 */
	setComponent( index, value ) {

		switch ( index ) {

			case 0: this.x = value; break;
			case 1: this.y = value; break;
			case 2: this.z = value; break;
			default: throw new Error( 'THREE.Vector3: index is out of range: ' + index );

		}

		return this;

	}

	/**
	 * Returns the value of the vector component which matches the given index.
	 *
	 * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
	 * @return {number} A vector component value.
	 */
	getComponent( index ) {

		switch ( index ) {

			case 0: return this.x;

View on GitHub (pinned to da05705fa3)

Solutions

  1. Keep the index within [0,2] for Vector3; branch or clamp first.
  2. Use Vector4 when you genuinely have four components.
  3. Derive loop bounds from the target vector's size.
  4. Set fields directly (vec.x/y/z) when the index is constant.

Example fix

// before: looping 4 components into a Vector3
for (let i = 0; i < 4; i++) v3.setComponent(i, data[i]); // i===3 throws

// after: bound to 3, or use Vector4
for (let i = 0; i < 3; i++) v3.setComponent(i, data[i]);
Defensive patterns

Strategy: validation

Validate before calling

function setComponentSafe(vec, index, value) {
  if (index < 0 || index > 2) {
    throw new RangeError(`Vector3 index must be 0-2, got ${index}`);
  }
  vec.setComponent(index, value);
  return vec;
}

Type guard

function isValidVector3Index(index) {
  return Number.isInteger(index) && index >= 0 && index <= 2;
}

Prevention

When it happens

Trigger: Calling vec3.setComponent(3, v) or any index outside [0,2]. Looping 4 times (e.g. feeding RGBA into a Vector3). Passing a Vector4's component index into a Vector3. Negative or NaN index.

Common situations: Shared generic loops sized for Vector4 applied to a Vector3. Deserialization of 4-component tuples. Indexing errors in math shaders mirrored on the CPU.

Related errors


AI-assisted analysis of mrdoob/three.js@da05705fa3 (2026-08-12). Data as JSON: /api/errors/0c12eaf7536ecc9d. Report an issue: GitHub.