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:

Subscripts translate into JavaScript array references.

Vector addition is then an array of array element additions:

Vector subtraction:

The dot product is a scalar value:

The cross product:

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.

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: