Find Area of a Triangle – JavaScript Solution

This is a preview lesson
Register or sign in to take this lesson.

Area of triangle

This tutorial shows a snippet for finding the area of a triangle. The formulae for finding area of triangle is:  ½ (b × h) 

Pseudo-code

areaOfTriangle = (1/2) * breadth * height        // returns the area of triangle

JavaScript Syntax

let areaOfTriangle = (1/2) * breadth * height;

Firstly, let’s look at assigning it to a variable after calculation.

let breadth = 10;
let height = 10;

let areaOfTriangle = (1/2) * breadth * height;
console.log(areaOfTriangle);          
/*
 * Output
 * prints 50 which is the area of the triangle which has breadth and height 10 and 10 respectively
*/

Now the the same code is wrapped around a function, making it possible to be dynamic.

// function that wraps the triangle area calculator 
function areaOfTriangle(breadth, height) {
    let area = (1/2) * breadth * height;
    return area;
}

let breadth = 4;
let height = 4;

console.log(areaOfTriangle(breadth * height));

/*
 *   Output
 *    prints 8 which is the area of the triangle which has breadth and height 4 and 4 respectively
*/

console.log(areaOfTriangle(5 * 5));

/*
 * Output
 * prints 12.5  which is the area of the triangle which has breadth and height 5 and 5 respectively
*/