Normalizing Vectors

Normalizing can be confusing because there are some slightly different, but similar meanings, in different dituations.

Normalizing vectors

Different to normalizing numbers, normalizing vectors is quite straight forward.

Lets take the example of the 2D vector [3,4];

Normalizing this means returning a new vector, the length of which is equal to 1. A vector of length 1 is also sometimes called a unit vector.

function normalize2D(v) {
  const x = v[0];
  const y = v[1];
  const len = Math.sqrt(x * x + y * y);
  return [x / len, y / len];

normalize2D([3, 4]);
// returns [0.6, 0.8]

To achieve this we get the length of the vector. Then divide the x and y component of the vector. This makes sense because, if the length is 5, as in the case above, the vector is five times too large. So we divide x by 5, and y by 5, giving us the correct vector.

Most frameworks will have vector helpers with a normalize function, but it's important to see what it is, and understand how it works.