[Solved] Calculate the area of triangle by its 3 sides in JavaScript

  

3
Topic starter

JS task: Write a JavaScript function that calculates a triangle’s area by its 3 sides.

  • The input comes as 3 (three) number arguments, representing one sides of a triangle.
  • The output should be printed to the console.

Example:

Input:
2
3.5
4

Output:
3.4994419197923547

1 Answer
2

For this task you must use the Heron's formula:

https://en.wikipedia.org/wiki/Heron%27s_formula

Here's my solution to it (with Heron's formula):

function triangleArea(a, b, c) {
    let sp = (a + b + c) / 2;
    let area = Math.sqrt(sp * (sp - a) * (sp - b) * (sp - c));
    console.log(area);
}
 
triangleArea(2, 4, 3.5);

Or with .map(Number) which transform all the elements of the array into numbers.

See line 2:

function areaTriangle([a,b,c]) {
    [a,b,c] = [a, b, c].map(Number);//.map is converting all the elements in the array into numbers
    let sp = (a + b + c) / 2;
    let area = Math.sqrt(sp * (sp - a) * (sp - b) * (sp - c));
    return area;
}
 
console.log(areaTriangle(["2", "3.5", "4"]));
Share: