JRS: In article <MP************************@news.highstream.net> , dated
Wed, 20 Jul 2005 09:23:16, seen in news:comp.lang.javascript, Wayfarer
<wf***************@SPAMyahoo.com> posted :
Can anyone please tell me how to do this correctly? I'm trying
to learn javascript and I've taken it as far as I can and I'm
extremely frustrated!
var L = prompt("Enter the length of carpet");
var W = prompt("Enter the width of carpet");
var C = prompt("Enter the cost per unit");
function carpet_cost(L,W,C)
{
var area = L * W;
var carpet_cost=(area * C);
}
return carpet_cost
window.alert ("The total cost of the carpet is", carpet_cost);
(1) Your return statement is after the function and should be within it;
(2) Method .alert takes a single (string) parameter; change the comma to
a plus;
(3) The call of carpet cost in the .alert() needs parentheses and
parameters.
With those changes, this works :
var L = prompt("Enter the length of carpet");
var W = prompt("Enter the width of carpet");
var C = prompt("Enter the cost per unit");
function carpet_cost(L,W,C)
{
var area = L * W;
var carpet_cost=(area * C);
return carpet_cost
}
window.alert
("The total cost of the carpet is" + carpet_cost(L, W, C));
Now improvements to your coding :
(a) It is confusing to use the same name for a function and a var in it;
change the latter to, say, CC;
(b) It is inappropriate to use the same name for a parameter inside and
outside a function; change the former;
(c) Code should be indented to show structure, and other spaces help;
(d) Parentheses are not needed around the multiplication;
(e) Inputs are essentially Numbers, so it is cleaner to convert to
Number immediately - see FAQ sec. 4.21.
var LoC = + prompt("Enter the length of carpet") ;
var WoC = + prompt("Enter the width of carpet") ;
var CpU = + prompt("Enter the cost per unit area") ;
function carpet_cost(L, W, C) {
var area = L * W ;
var CC = area * C ;
return CC }
window.alert("The total cost of the carpet is" +
carpet_cost(LoC, WoC, CpU)) ;
The function can be simplified to
function carpet_cost(L,W,C) { return L * W * C }
Given typical widths, lengths, and prices, you should need to display in
customary currency format - see FAQ, sec 4.6.
Inputs should be validated as being numbers of reasonable format - see
<URL:http://www.merlyn.demon.co.uk/js-valid.htm>.
It would be better to use a form with <input type=text ...> for
input and output, and a button for calculation.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.