Member-only story
Calculating the area of shapes gets back to basics from geometry class. But when you just want the triangle area result without the formula every time? We’ve got you covered!
In this quick article, we’ll write a handy JavaScript function to figure out that areas for us by taking in just the base and height as arguments. No pencil or calculator required!
Defining the Function
First, let’s outline the function and parameters:
function triangleArea(base, height) {
}
By defining base and height inside the parentheses, we tell the function to accept those values as inputs.
Calculating the Area
Inside the function body, we simply multiply base * height / 2:
function triangleArea(base, height) {
var area = base * height / 2;
}
This applies the standard geometry formula for any triangle’s area!
Returning the Result
We finish by returning the area value out of the function:
function triangleArea(base, height) {
var area =…