Why do I get the min can only expected only 2 argument but received 4 even though it works like a dream?

I made a function that rounds numbers to the nearest number of your choice using dist and min, whenever the program does the min math it tells me that min can only receive 2 arguments, but it still works? It’s not a problem just wondering what is going on if anyone knows.

<function setup() {
createCanvas(400, 400);
}

function draw() {
text(roundTo(36,10,20,30,40),200,200);
}

function roundTo(n,op1,op2,op3,op4){
let op1dis = dist(op1,0,n,0);
let op2dis = dist(op2,0,n,0);
let op3dis = dist(op3,0,n,0);
let op4dis = dist(op4,0,n,0);

min(op1dis,op2dis,op3dis);
if(min(op1dis,op2dis,op3dis,op4dis) == op1dis){
n = op1;
}
if(min(op1dis,op2dis,op3dis,op4dis) == op2dis){
n = op2;
}
if(min(op1dis,op2dis,op3dis,op4dis) == op3dis){
n = op3;
}
if(min(op1dis,op2dis,op3dis,op4dis) == op4dis){
n = op4;
}

return n;
}>

Hi,

If you run this sketch in the p5 web editor, you get this error message :

🌸 p5.js says: min() was expecting no more than 2 arguments, but received 4. 
(on line 86 in about:srcdoc [about:srcdoc:86:10]). 
(http://p5js.org/reference/#/p5/min) 

It gives the documentation link of the min() function :

Syntax

min(n0, n1) n0 and n1 as numbers

min(nums) nums is a list of numbers

So you have two different syntax. But in your case you are giving the function more parameters that it can use. In JavaScript if you give more parameters to a function, it works but you never use them :

function test(a, b) { console.log(arguments) }

test(0, 1, 2, 3);

// output -> Object {0: 0, 1: 1, 2: 2, 3: 3}

(see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)

luckily p5js gives you a warning :wink:

1 Like

So I should change my variables and put them into and array or something? , I know about the p5js website and that is where I get my info from but it works for some reason. Thank you, i’ll look into it.

So yeah if you want to compute the minimum between 4 values, you can put them in an array for the min() function.

If you really want to pass them as arguments, you can do it like this :

function minFromArgs(...args) {
  return min(args);
}

print(min(1, 6, -1, 3)); // -> -1

It’s using this syntax : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

1 Like