Vector handling in JavaScript

To make this happen in code, we'll need to perform 3D vector mathematics.

High-quality JavaScript vector libraries do exist. However, the textbook does not use one. To minimize dependencies, all necessary vector-handling is defined as simply as possible here.

Represent a 3D vector as a 3-element JavaScript array. This approach matches the use of nested arrays for geometry representation. For example:

var a = [1, 0, 0];
var b = [0, 1, 0];

Subscripts translate into JavaScript array references.

$a_x$ ≡ a[0]
$a_y$ ≡ a[1]
$a_z$ ≡ a[2]

Vector addition is then an array of array element additions:

$\V{a}+\V{b}$ ≡ [a[0] + b[0], a[1] + b[1], a[2] + b[2]]

Vector subtraction:

$\V{a}-\V{b}$ ≡ [a[0] − b[0], a[1] − b[1], a[2] − b[2]]

The dot product is a scalar value:

$\V{a}\cdot\V{b}$ ≡ a[0] * b[0] + a[1] * b[1] + a[2] * b[2]

The cross product:

$\V{a}\times\V{b}$ ≡ [
  a[1] * b[2] − a[2] * b[1],
  a[2] * b[0] − a[0] * b[2],
  a[0] * b[1] − a[1] * b[0]
]

To write each of these operations out in full with each use would lead to lengthy and error-prone programs. It's best to translate each of these into a separate JavaScript function.

〈Vector Operations〉 ≡
  function add(a, b) {
    return [
      a[0] + b[0],
      a[1] + b[1],
      a[2] + b[2]
    ];
  }

Implementations of vector subtraction, dot product, and cross product will be similar.

Additionally, vector normalization is extremely common. Given a JavaScript function for the dot product, a normalize function might look like this:

  function normalize(a) {
    var len = Math.sqrt(dot(a, a));
    return [
      a[0] / len,
      a[1] / len,
      a[2] / len
    ];
  }