I tried it using making an array first and then choosing max out of it but the output is always NaN
<!DOCTYPE html>
<html>
<body>
<h2>Write a function in JavaScript which accept three numbers as arguments and
display the greatest number.</h2>
<p id="demo"></p>
<script>
selnum = [num1, num2, num3];
var num1 = prompt("Please wirte any number");
var num2 = prompt ("Please write 2nd number");
var num3 = prompt("Please wirte 3rd number");
document.write(Math.max(selnum));
</script>
</body>
</html>
There are multiple solutions.
You can do it with an Array, or with only var.
With array:
var num1 = prompt("Please write any number");
var num2 = prompt("Please write 2nd number");
var num3 = prompt("Please write 3rd number");
var arr = [num1, num2, num3];
document.write(Math.max(...arr));
With var:
var num1 = prompt("Please write any number");
var num2 = prompt("Please write 2nd number");
var num3 = prompt("Please write 3rd number");
document.write(Math.max(num1, num2, num3));
If you don't want to you Math.max you can do:
var num1 = prompt("Please write any number");
var num2 = prompt("Please write 2nd number");
var num3 = prompt("Please write 3rd number");
var arr = [num1, num2, num3];
var maxi = num1;
for(let i = 1; i < arr.length; i++){
maxi = (maxi < arr[i] ? arr[i] : maxi);
}
document.write(maxi);
With a function it will look something like:
function f(num1, num2, num3){
return Math.max(num1, num2, num3); // Without array
}
Found this as the working one
<script>
var num1 = prompt("Please wirte any number");
var num2 = prompt("Please write 2nd number");
var num3 = prompt("Please wirte 3rd number");
document.write(Math.max(num1, num2, num3));
</script>
Your selnum = [num1, num2, num3];
is happening before you actually get the numbers from the user. You need to put that line after the prompt()
lines.
You may also need to convert the values to numbers, as prompt()
always returns a string and these may not sort the way you expect.
Finally, Math.max
doesn't accept an array, it accepts an unlimited number of parameters. So you need to use .apply
here.
var num1 = prompt("Please wirte any number");
var num2 = prompt("Please write 2nd number");
var num3 = prompt("Please wirte 3rd number");
var selnum = [parseInt(num1, 10), parseInt(num2, 10), parseInt(num3, 10)];
console.log(Math.max.apply(Math, selnum));
Also, document.write
really isn't used anymore. Use console.log
and check your developer console in the browser.