The wrong result

Hi

I enter 4 and 3. The perimeter will have 14. But I see 86. Why?


// Calculation of the perimeter box
var perimeterBox = function(height, width) {
    return 2*(height+width);
};

// Input data
var height = prompt("Enter a height value:", "Write a height value here");
var width = prompt("Enter a width value:", "Write a width value here");

// Processing data
var parimeter = perimeterBox(height, width);

// Output data
confirm("The perimeter of a box (with: height = " + height +
        " and width = " + width + ") is " + perimeter);

Thank you!

Hi,

Because the values being passed to your perimiterBox() function are both strings.
To perform the calculation you’ll have to convert them to numbers, e.g.

var perimeterBox = function(height, width) {
  return 2 * ( Number( height ) + Number( width ) );
};

or a slightly shorter way of converting the strings to numbers:

var perimeterBox = function(height, width) {
  return 2 * ( (+height ) + (+width ) );
};

Thank you very much, guys!

It works too:


var perimeterBox = function(height, width) {
    return 2*(parseFloat(height)+parseFloat(width));
};

Hi felgall,

That’s a unary plus, right?
Is there any advantage to using that over Number, other than the obviously shorter syntax?

Yes it is a unary plus - the advantage of using it is that it is shorter. I don’t know of any other advantage but I don’t see any need to type six characters when one will do the same thing. I would not have posted that version without the version using Number also being posted as the unary plus code is basically a short version of that just as ‘’+ is a short version of String().

Oh ok, thanks.
I didn’t know the "+ notation either.