Question on 9/13 Functions with two parameters


#1

Playing around, I compared my first solution with a different approach (see code below). I noticed however that with console.log only half the output is given (4 instead of 8). I was wondering why this was the case. It doesn't do this with return.

The feedback commentary on save & submit was:

Oops, try again.
It looks like your perimeterBox function doesn't return the correct perimeter (4) for a width of 1 and a length of 1.


// Write your function starting on line 3

var perimeterBox = function (length, width) {
return length * 2 + width * 2;
};
perimeterBox(1, 3);

var perimeterBox = function (length, width) {
var val = length * 2 + width * 2;
//return val
console.log(val);
};
perimeterBox(1, 3);


#2

I ran your code to confirm it anyway. I could see nothing wrong with it initially. There is no problem.
Are you sure you did'nt have some other value in there when you ran it initially ?


#3

Yes, I had the code just as I posted. In fact, I just tried it again and I get the same output. However, if I put the console.log variant

var perimeterBox = function (length, width) {
var val = length * 2 + width * 2;
//return val
console.log(val);
};
perimeterBox(1, 3);

above this one:

var perimeterBox = function (length, width) {
return length * 2 + width * 2;
};
perimeterBox(1, 3);

Then I only get 8 and 8 as output. Not 8 and 4. Could they be interacting with each other?


#4

Answer: No. The second one is overwriting the first. JS doesn't care, though, since perimeterBox is just a variable reference to an anonymous function. We can redefine the variable all we wish. Generally speaking, though, we should only ever declare a variable once, and when defining it with a function, keep the function intact.

On the whole, we should be getting comfortable with the return statement in our functions, and move away from console.log(). That way our functions are portable and can work behind a web page, when that time comes.

var perimeterBox = function (length, width) {
    return 2 * (length + width);
}
console.log(perimeterBox(1,3);    // 8