Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write a function in JavaScript which accept three numbers as arguments and display the greatest number

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading