1 minute
Contact me

## What is a vector?

In the Euclidean sense a vector is something that has magnitude and direction.

The size of the vector is the magnitude and the direction is the angle in relation to an x axis running adjacent to the vector.

A vector doesn't necessarily have to be expressed as a magnitude and a direction it can also be expressed as an x and y pair.

An quick example by Johan Karlsson:

See the Pen A Vector by Johan Karlsson (@DonKarlssonSan) on CodePen.

Watching this animation really helped me wrap my head around the idea that x and y positions can also be represented by vectors, So I am sharing it in the hopes it will do the same for you.

However changing the x and y values all the time isn't exactly efficient. We normally end up adding things to the x an y to create speed or position etc until there are many functions and variables to keep track of.

Now with an understanding of vectors we can represent the position as a vector.

Here's a simple example and refactor. Take this boucing ball for example:

See the Pen Simple Bouncing Ball X,Y by Adam Harpur (@harps116) on CodePen.

The ball has an x and y that is increased or decreased depending on it's location on the canvas. With this approach we are constantly checking and updating the and x and y variables.

Refactor using vectors:

See the Pen Simple Bouncing Ball Vector by Adam Harpur (@harps116) on CodePen.

With this approach we encapsulate all the logic into a ball constructor and create a new instance on setup, we then call the move and show methods. The move method checks the balls location and adjusts the velocity vector based on the boundaries of the canvas, that adjusted vector is then added to the balls location.

It's best to checkout the links to see the full functionality.

Happy Coding!