Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.max() not working as expected

Tags:

javascript

I have this following function, where Math.max() is not working as expected. It is always alerting the 1st value from the arguments that are passing. Where is the mistake?

function large(arr) {
   alert(Math.max(arr))
}

large(1,2,3,4,5);
like image 776
krishna teja Avatar asked Aug 27 '26 15:08

krishna teja


2 Answers

You are passing multiple arguments, but your function only uses the first one.

In ES5 and before, you can use the apply method of a function and the arguments object:

function large() { 
   alert(Math.max.apply(Math, arguments)) 
} 

large(1,2,3,4,5);

In ES6 you can use the rest and spread operator:

function large(...arr) { 
   alert(Math.max(...arr)) 
} 

large(1,2,3,4,5);
like image 98
Alexander O'Mara Avatar answered Aug 29 '26 06:08

Alexander O'Mara


You can do like this.

If you want to use the arguments you can avoid the parameter of the function. Then use the apply function to call Math.max

function large() {
var _max = Math.max.apply(Math, arguments);
alert(_max)
};
large(1, 2, 3, 4, 5, 20,9000);

DEMO

like image 41
brk Avatar answered Aug 29 '26 05:08

brk