Introduction to functions in JS - 9. Functions with two parameters


#1


Hey guys


I'm just doing exercise 9 Functions with two parameters in introduction to functions in JS. I can get passed this exercise but I wanted to try and get the values for both parameters by prompts.


My function is to produce the perimeter by acquiring the length and width by prompt. The function currently is adding the numbers like 5 + 7 = 57, opposed to 12.

For example, if I want the perimeter and I put my length as 5 and width as 7, the perimeter would come out as 114 because 57 * 2 = 114, opposed to 12 * 2 = 24

Can anyone show me the correct code? Cheers in advance


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

var askLength = prompt ("What is the length?");
var askWidth = prompt ("What is the width?");

perimeterBox (askLength, askWidth);


#2

What does your code above return?


#3

When I put in the length as 5 and the width as 7, I get 114 as the perimeter.

I think my code is putting 5 and 7 together as 57 and then multiplying by 2 to get 114.

Instead of 2 * (5+7) = 24

When I don't use prompts and instead just call perimeterBox(5,7), I get 24 in return.


#4

Yes you are correct,

you can fix this error by using the parseInt() Javascript method,

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

var askLength = parseInt(prompt ("What is the length?"));
var askWidth = parseInt(prompt ("What is the width?"));

perimeterBox (askLength, askWidth);

#5

Thanks ! I will have a google into this parseInt() Javascript method :smiley:


#6

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