settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Calculate the area of triangle by its 3 sides in JavaScript

+4 votes

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

asked in JavaScript category by user samfred5830

3 Answers

+3 votes

Use the image below to see the formula:

area of a triangle - formula

answered by user sam
+1 vote

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);
answered by user eiorgert
edited by user golearnweb
+1 vote

MIne is 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"]));
answered by user matthew44
edited by user golearnweb
...