9. Functions with two parameters question, thanks!


I understand the code#1 below is correct, but why is the second code wrong? why can't i add another var as the orange cost or divideByThree example? Thank you!!

var perimeterBox = function (p1, p2){
return p1+p1+p2+p2;
perimeterBox(4, 2)

var perimeterBox = function (p1, p2){
var val = p1+p1+p2+p2;
perimeterBox(4, 2)


Almost correct. Anything after return is unreachable. The function does not need to log anything so that line can be removed.

No need to. It will only be destroyed as soon as the function is exited. A straight forward return statement is sufficient. The computed value will be sent back to the caller. If you wish to log out the result, then log the function call expression:

console.log(perimeterBox(4,2));    // 12

Side note: When selecting variable names, use what best describe the arguments being passed in... length and width are the two concepts in play here. No need to obfuscate with indeterminant variables like p1 and p2. Those terms describe nothing.

var perimeterBox = function (length, width) {
    return ...

The example gives length + length + width + width which is correct, but when we see repetition in math, we simplify as a general rule. Your teacher probably harps about this if you are studying algebra.

p = a + a + b + b

but a + a is 2 * a; and, b + b is 2 * b

p = 2a + 2b

factoring out the 2 gives,

p = 2 * (a + b)


return 2 * (length + width);


Thank you so much ~ great answer!!! !


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.