Shoelace formula for polygon area in JavaScript
Intermediate · 4 min read
The area of a rectangle is easy. The area of a field with five crooked edges, a room shaped like an L, or a region drawn on a map is not, unless you know the shoelace formula. Give it the corners of any polygon (a flat shape with straight edges) in order, and it gives you the area. It is used in mapping software, games and drawing apps.
In this tutorial you will write the shoelace formula and try it on a square, a triangle, an L-shape and a five-sided figure. You will find out what it means when the answer comes out negative. Then you will move a shape a billion units away and watch its area go wrong. You need to know arrays of [x, y] pairs, for loops and %.
The idea
List the corners, called vertices, in order around the shape. For each edge, from one vertex (x1, y1) to the next (x2, y2), work out:
x1 * y2 - x2 * y1
Add these up for every edge, including the last edge back to the first vertex, and halve the total. That's the area. The name comes from the pattern: if you write the coordinates in two columns and draw the multiplications, the lines cross like the laces of a shoe.
The sign
The sum comes out positive if you went around the shape counter-clockwise and negative if you went clockwise. The size is the same either way. So the sign tells you the direction you walked, which is called the winding.
Here is the exercise. If you'd like to try it first, go ahead. Otherwise, read on and we will build it together.
98 The shoelace formula, and what its sign is for
fairFind the area of a polygon from its vertices with the shoelace formula. Do a square, a triangle, an L-shape and a five-sided figure, and say what the sign of the result tells you. Then translate one polygon a long way from the origin and see whether the area survives.
Stuck? Three hints, smallest first
- 1. Sum
x1 * y2 - x2 * y1over every edge, wrapping the last vertex to the first, and halve it. - 2. Reverse the vertex order and the answer changes sign but not magnitude.
- 3. Every term is a product of coordinates, so shifting the polygon makes those products huge and nearly equal.
Step 1: the formula
const shoelace = (points) => {
let sum = 0;
for (let i = 0; i < points.length; i++) {
const [x1, y1] = points[i];
const [x2, y2] = points[(i + 1) % points.length];
sum += x1 * y2 - x2 * y1;
}
return sum / 2;
};
const square = [[0, 0], [4, 0], [4, 4], [0, 4]];
console.log(shoelace(square)); // 16
(i + 1) % points.length is the index of the next vertex. On the last vertex it wraps around to 0, so the closing edge back to the start is included.
For the 4 by 4 square, the four edges give 0, 16, 16 and 0. The total is 32, and half of that is 16.
Step 2: the sign is the winding
console.log(shoelace([...square].reverse())); // -16
const area = (points) => Math.abs(shoelace(points));
const isCounterClockwise = (points) => shoelace(points) > 0;
console.log(isCounterClockwise(square)); // true
Reverse the vertices and you walk the other way, so the answer flips to -16. area drops the sign with Math.abs. isCounterClockwise keeps it and reads it. [...square] copies the array first, because reverse changes an array in place.
Step 3: a triangle and an L-shape
const triangle = [[0, 0], [4, 0], [0, 3]];
console.log(shoelace(triangle), (4 * 3) / 2); // 6 6
const lShape = [[0, 0], [6, 0], [6, 2], [2, 2], [2, 5], [0, 5]];
console.log(shoelace(lShape)); // 18
The triangle matches base times height over two. The L-shape is concave: it has a corner that points inward. You might expect to cut it into two rectangles first, but there is no need. The formula handles it directly: a 6 by 2 strip (12) plus a 2 by 3 block (6) is 18.
Step 4: a five-sided figure
const pentagon = [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]];
console.log(shoelace(pentagon), area(pentagon)); // -30 30
console.log(isCounterClockwise(pentagon)); // false
The answer is -30, so these vertices were listed clockwise, and the area is 30. In mapping data, the winding tells you which side of a boundary is inside, so the sign is often as useful as the area.
Step 5: two edge cases
console.log(shoelace([...square, [0, 0]])); // 16
console.log(shoelace([[0, 0], [1, 1], [2, 2]])); // 0
Some data formats repeat the first vertex at the end to "close" the shape. That adds an edge from [0, 0] to [0, 0], whose term is 0, so the answer doesn't change. Three points on one straight line enclose nothing, and the area is 0.
Step 6: a long way from the origin
Moving a shape doesn't change its area. Let's check.
const translate = (points, dx, dy) => points.map(([x, y]) => [x + dx, y + dy]);
console.log(shoelace(translate(pentagon, 1000, 1000))); // -30
console.log(shoelace(translate(pentagon, 1e9, 1e9))); // -128
A thousand units away, still -30. A billion units away, it says -128.
Each term is x1 * y2 - x2 * y1. Far from the origin, both products are around 1e18, huge and nearly equal. A JavaScript number holds only about 16 significant digits, so subtracting two nearly equal huge numbers leaves mostly rounding error. This is called cancellation. It matters in real life: map coordinates measured in meters are often seven or eight digits long.
Step 7: the fix
Shift the shape so its first vertex sits at the origin, then measure. The area doesn't change, but now the numbers are small.
const shoelaceShifted = (points) => {
const [x0, y0] = points[0];
return shoelace(translate(points, -x0, -y0));
};
console.log(shoelaceShifted(translate(pentagon, 1e9, 1e9))); // -30
Subtracting x0 from 1000000003 gives 0, and from 1000000005 gives 2, both exactly. So the shifted shape is exactly the original pentagon moved, and the area is right again.
The full solution
The answer panel has shoelace, area, isCounterClockwise, translate and a perimeter helper, and prints every shape above, a unit hexagon, both edge cases and the pentagon moved by 1000 and by 1e9. Press Run to see the output.
const shoelace = (points) => {
let sum = 0;
for (let i = 0; i < points.length; i++) {
const [x1, y1] = points[i];
const [x2, y2] = points[(i + 1) % points.length];
sum += x1 * y2 - x2 * y1;
}
return sum / 2;
};
const area = (points) => Math.abs(shoelace(points));
const isCounterClockwise = (points) => shoelace(points) > 0;
const translate = (points, dx, dy) => points.map(([x, y]) => [x + dx, y + dy]);
const perimeter = (points) =>
points.reduce((s, p, i) => {
const q = points[(i + 1) % points.length];
return s + Math.hypot(q[0] - p[0], q[1] - p[1]);
}, 0);
const square = [[0, 0], [4, 0], [4, 4], [0, 4]];
const triangle = [[0, 0], [4, 0], [0, 3]];
const lShape = [[0, 0], [6, 0], [6, 2], [2, 2], [2, 5], [0, 5]];
const pentagon = [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]];
const hexagon = Array.from({ length: 6 }, (unused, i) => [
Math.cos((i * Math.PI) / 3),
Math.sin((i * Math.PI) / 3),
]);
console.log('square, both windings:', shoelace(square), shoelace([...square].reverse()));
console.log('triangle :', shoelace(triangle), 'base times height over 2 =', (4 * 3) / 2);
console.log('L-shape :', shoelace(lShape), 'perimeter', perimeter(lShape));
console.log('pentagon :', shoelace(pentagon), '<- negative, so clockwise');
console.log('unit hexagon :', shoelace(hexagon), 'against 3 root 3 over 2 =', (3 * Math.sqrt(3)) / 2);
console.log('repeating the first point:', shoelace([...square, [0, 0]]));
console.log('three collinear points :', shoelace([[0, 0], [1, 1], [2, 2]]));
console.log('pentagon moved by 1000 :', shoelace(translate(pentagon, 1000, 1000)));
console.log('pentagon moved by 1e9 :', shoelace(translate(pentagon, 1e9, 1e9)), '<- was -30');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a 4 by 4 square has signed area 16 one way round and -16 the other', [shoelace(square), shoelace([...square].reverse())], [16, -16]);
test('so the sign is the winding direction and the magnitude is the area', [isCounterClockwise(square), isCounterClockwise(pentagon), area(pentagon)], [true, false, 30]);
test('the triangle agrees with base times height over two', [shoelace(triangle), shoelace(triangle) === (4 * 3) / 2], [6, true]);
test('a concave L-shape needs no decomposition: the formula just works', [shoelace(lShape), perimeter(lShape)], [18, 22]);
test('a unit-radius hexagon comes out at 3 root 3 over 2, exactly', [shoelace(hexagon), shoelace(hexagon) === (3 * Math.sqrt(3)) / 2], [2.598076211353316, true]);
test('repeating the first vertex at the end adds a zero term and changes nothing', shoelace([...square, [0, 0]]), 16);
test('three collinear points enclose nothing, and give a clean zero', [shoelace([[0, 0], [1, 1], [2, 2]]), Object.is(shoelace([[0, 0], [1, 1], [2, 2]]), 0)], [0, true]);
test('moving the pentagon a thousand units away leaves the area untouched', shoelace(translate(pentagon, 1000, 1000)), -30);
test('moving it a billion units away destroys it: -30 becomes -128', shoelace(translate(pentagon, 1e9, 1e9)), -128);
The shoelace formula is the cross-product idea from exercise 79 summed round a loop, and it has two properties worth more than the area itself. It handles concave polygons with no special casing — the L-shape needs no decomposition into rectangles. And its sign is the winding direction: positive for counter-clockwise, negative for clockwise. That sign is how you normalise polygon orientation, decide which side of an edge is inside, and detect a self-inverted ring in geographic data.
Because the wrap uses (i + 1) % points.length, an explicitly closed ring with the first vertex repeated at the end contributes an extra zero term and the answer is unchanged. That is worth knowing, because GeoJSON rings are closed and most textbook examples are not.
The last assertion is the one to remember. Every term is x1 * y2 - x2 * y1, so translating the polygon far from the origin makes each product enormous while their difference stays small — cancellation again, the same failure as the one-pass variance in exercise 94. A pentagon of area 30 sitting at a billion units out computes as 128. Real coordinate data lives in exactly that regime: UTM eastings and web-mercator metres are seven and eight digits. The fix is one line — subtract the first vertex from all of them before summing, so the arithmetic happens near the origin.
Common mistakes
- Leaving out the closing edge. Without the wrap from the last vertex back to the first, the area is wrong. Use
(i + 1) % points.length. - Throwing the sign away too early. The sign tells you the winding. Use
Math.absonly when you want the area alone. - Using raw map coordinates. Far from the origin, the products cancel. Shift the shape near the origin first.
Try it yourself
- Find the area of a right-angled trapezoid with corners
[0, 0],[8, 0],[5, 4],[0, 4]. Check it with (8 + 5) / 2 * 4. - Write
ensureCounterClockwise(points)that reverses the list only when it is clockwise. - Move the L-shape by 1e9 in both directions and compare
shoelacewithshoelaceShifted.