Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript max() function for 3 numbers

I need to find the highest number from 3 different numbers. The only thing I've found is max() but you can only use 2 numbers.

Whats the best way?

like image 273
Ben Shelock Avatar asked Sep 13 '09 18:09

Ben Shelock


People also ask

Can math Max take 3 values?

max only takes two arguments. If you want the maximum of three, use Math.

How do I compare 3 numbers in JavaScript?

To compare 3 values, use the logical AND (&&) operator to chain multiple conditions. When using the logical AND (&&) operator, all conditions have to return a truthy value for the if block to run. Copied!

How do you find the largest number in JavaScript with 3 numbers?

Math. max() returns the largest number among the provided numbers. You can use Math. min() function to find the smallest among the numbers.

Is there a max function in JavaScript?

max() The Math. max() function returns the largest of the zero or more numbers given as input parameters, or NaN if any parameter isn't a number and can't be converted into one.


4 Answers

The Math.max function can accept any arbitrary number of arguments:

Syntax:

Math.max([value1[,value2[, ...]]]) 

Usage:

var max = Math.max(num1, num2, num3);

For example:

console.log(Math.max(1,2,3,4,5,6)); //  6

You could even use it to get the maximum value of an array of numbers with the help of apply:

function maxOfArray(array) {
  return Math.max.apply(Math, array);
}


let array = [1,2,3,4,5,6];
console.log(maxOfArray(array)); // 6

If you can target ES6 (ES2015), you can also use the spread operator:

let array = [1,2,3,4,5,6];
let max = Math.max(...array);
console.log(max); // 6
like image 121
Christian C. Salvadó Avatar answered Oct 23 '22 13:10

Christian C. Salvadó


In almost any language, one can use max twice:

Math.max(num1, Math.max(num2, num3))

As @CMS points out, JavaScript specifically allows an arbitrary number of parameters to Math.max:

Math.max(num1, num2, num3);
like image 21
Eric J. Avatar answered Oct 23 '22 12:10

Eric J.


Push your values into an array arr and use Math.min.apply(null, arr) or Math.max.apply(null, arr) for maximum and minimum values respectively:

var arr = [];
arr.push(value1);
arr.push(value2);
arr.push(value3);

var minValue = Math.min.apply(null, arr);
var maxValue = Math.max.apply(null, arr);
like image 41
Scott Pelak Avatar answered Oct 23 '22 11:10

Scott Pelak


Using with the new spread operator

var num = [23,34,56,72,1,22]; 
Math.max(...num)

for more info

like image 42
Ashish Yadav Avatar answered Oct 23 '22 12:10

Ashish Yadav