# Calculate the angle between two vectors in JavaScript

Given two vectors, you can calculate the angle between them using a few simple math operations. All you need to do is calculate the magnitude of each vector, the scalar product of the two vectors and use the arccosine function to get the theta value.

Simply put, you can use `Math.hyptot()` to calculate the magnitude of each vector, then multiply the corresponding elements of the two vectors and sum them up. Then, use `Array.prototype.reduce()` to calculate the scalar product of the two vectors. Finally, divide the scalar product by the product of the magnitudes of the two vectors and pass the result to `Math.acos()` to get the angle in radians.

```const vectorAngle = (x, y) =>
Math.acos(
x.reduce((acc, n, i) => acc + n * y[i], 0) /
(Math.hypot(...x) * Math.hypot(...y))
);

vectorAngle([3, 4], [4, 3]); // 0.283794109208328```

## More like this

• Collection · 4 snippets

### JavaScript Geometric Operations

Learn how to perform some basic geometric operations in JavaScript with this collection of snippets.

• JavaScript ·

### Calculate the Euclidean distance in JavaScript

Use JavaScript's `Math.hypot()` to calculate the Euclidean distance between two points.

• JavaScript ·

### How can I calculate the greatest common divisor & least common multiple in JavaScript?

Use JavaScript to calculate the greatest common divisor and least common multiple of two or more numbers.

• JavaScript ·

### Calculate the quotient and remainder of a division in JavaScript

Implement Python's `divmod()` built-in function in one line of JavaScript.

Start typing a keyphrase to see matching snippets.