max(){} function help

+4 James Moore · November 21, 2014
Define a function
max()
that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Javascript

<script type="text/JavaScript">
var a = prompt("enter a number");
var b = prompt("enter a second number"); 


if(a > b){
alert(a + " is the greater number")
}else{
alert( b +" is the greater number");

}

not sure how to encorp a function in this max(a,b){}?? 

Post a Reply

Replies

Oldest  Newest  Rating
+1 Marie Goodwyn · November 21, 2014
This may be what you want but I am not sure. I added a document.write so you can see what number is written.


<title>Untitled Document</title>
<script type="text/JavaScript">
var a = prompt("enter a number");
var b = prompt("enter a second number");

function max(a,b){
if(a > b){
alert(a + " is the greater number")
return a;
}else{
alert( b +" is the greater number");
return b;
}

}

document.write(max(a,b));
</script>
+1 James Moore · November 22, 2014
perfect thank you Marie ! i kept getting errors and i wasnt sure how to pas the variables a and b through the function.... javascript is weird sometimes, question though how do i trouble shoot my code in the browser? when writing javascript..... i remember in class we usto use a error console of some sort? i cant remember how to access that. but thank you very much :)
+1 Marie Goodwyn · November 23, 2014
If you are on Chrome, use crtl-shift-j
+1 James Moore · November 24, 2014
Thank you,m my next challenge was to add another number to the mix :$ worked out great heres my code 

<title>Untitled Document</title>
<script type="text/JavaScript">
var a = prompt("enter a number");
var b = prompt("enter a second number");
var c = prompt("enter a third number"); 


function max(a,b,c){
if(a > b && a > c){
alert(a + "  is the greater number");
return a;
}else if(b > a && b > c){
alert(b +"  is the greater number");
return b; 
}else{
alert( c +"  is the greater number");
return c;
}

}

document.write(max(a,b,c));
</script>
+1 Landon Luman · November 26, 2014
The If() alert needs a semi colon
0 Sochima Biereagu · January 10, 2015
<script>
function max()
{
return Math.max.apply(Math, arguments);

//arguments=> the arguments passed in
}

alert( max("5","9","-1","6") ); //9
</script>
  • 1

Javascript

107,233 followers
About

A scripting language that is added to standard HTML to create interactive effects, apps, games for the browser.

Links
Moderators