SuperSafie
SuperSafie

Reputation: 74

Reference stored values

I'm brand new to the JS world and writing code to determine the area of a triangle given 3 of it's sides. I know that there's probably an easier way of doing what I'm trying to do, but I like learning this way. I want the first function to store the value it obtained from the calculation so I can use it in the second function. I feel that there have to be an easier way to reference the value obtained in a previous function. Thanks.

const cosA = function(a,b,c) {
    return (((b * b ) + (c * c) - (a * a)) / ((2 * b) * c));
}
console.log(cosA(5,6,7));
// --> 0.7142857142857143

const aRad = function() {
    return (Math.acos(cosA(5,6,7)));
}
console.log(aRad());
// --> 0.7751933733103613

Upvotes: 0

Views: 47

Answers (2)

Guilherme Vieira
Guilherme Vieira

Reputation: 507

Well, you want to use a variable. Just declare it using let and assign to it the value returned from the first function. The second function needs to receive arguments, just like the first one, but in this case only one.

Which is what @trincot just answered.

Mathematically, though, you can calculate the area of a triangle given its three sides using Heron`s formula: https://en.wikipedia.org/wiki/Heron%27s_formula.

Upvotes: 0

trincot
trincot

Reputation: 350310

You'll want to pass an argument to the function aRad so it does its job for a given value. Then just assign any result you want to keep to a new variable:

const aRad = function(cosine) {
    return Math.acos(cosine); 
}

But now aRad is so much like Math.acos it does not really add much value. So just not do that.

const cosine = cosA(5,6,7);
console.log(cosine);

const rad = Math.acos(cosine); // or aRad(cosine) if you really want ;)
console.log(rad);

Upvotes: 1

Related Questions