TheAlgorithms/JavaScript · error · Error

Cannot normalize vectors of length 0

Error message

Cannot normalize vectors of length 0

What it means

Thrown by Vector2.normalize() (plain Error) when the vector's length (magnitude sqrt(x*x + y*y)) is exactly 0, i.e. x === 0 && y === 0. Normalization divides by length, so a zero vector would divide by zero; the library refuses to produce a NaN/undefined direction.

Source

Thrown at Data-Structures/Vectors/Vector2.js:55

  /**
   * Vector length.
   *
   * @returns The length of the vector.
   */
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y)
  }

  /**
   * Normalization sets the vector to length 1 while maintaining its direction.
   *
   * @returns The normalized vector.
   */
  normalize() {
    const length = this.length()
    if (length === 0) {
      throw new Error('Cannot normalize vectors of length 0')
    }
    return new Vector2(this.x / length, this.y / length)
  }

  /**
   * Vector addition
   *
   * @param vector The vector to be added.
   * @returns The sum-vector.
   */
  add(vector) {
    const x = this.x + vector.x
    const y = this.y + vector.y
    return new Vector2(x, y)
  }

  /**
   * Vector subtraction

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Check vector.length() === 0 (or x === 0 && y === 0) before normalize().
  2. Return a default unit vector (e.g. (1,0)) instead of normalizing when the input is zero.
  3. Validate that the source points are distinct before deriving a direction from their difference.
  4. Add an epsilon check (length < 1e-12) if floating-point near-zero magnitudes are possible.

Example fix

// before
const dir = v.normalize() // throws when v is (0,0)

// after
const dir = v.length() === 0 ? new Vector2(1, 0) : v.normalize()
Defensive patterns

Strategy: validation

Validate before calling

function safeNormalize(v, fallback = new Vector2(1, 0)) {
  return v.length() === 0 ? fallback : v.normalize()
}

Type guard

const isNonZeroVector = (v) => v.length() !== 0

Try / catch

try {
  return v.normalize()
} catch (e) {
  if (e instanceof Error && /length 0/i.test(e.message)) return new Vector2(1, 0)
  throw e
}

Prevention

When it happens

Trigger: Calling normalize() on new Vector2(0, 0); on a vector obtained by subtracting two identical points; on a default/zero-initialized vector that was never assigned real components.

Common situations: Direction vectors computed from (b - a) where a === b; physics/animation where an object's velocity is zero at rest; sensors returning 0,0 during initialization.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/ab4aa563c44947fc. Report an issue: GitHub.