-4

How do I compare values of spread argument with some value?

For example:

var arr = [1, 4, 10];

if(Math.min(...arr) > 1) {
  console.log('Must be greater than 1');
}

is giving me undefined. Naturally same with Math.max(...arr).

Same happens if I do:

var val = Math.min(...arr);

and then compare variable with some value.

Why?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
tholo
  • 511
  • 3
  • 8
  • 19
  • 1
    Your posted code works... – mhodges Jul 10 '17 at 19:36
  • 1
    Maybe you're testing this in an environment where spread operators aren't supported. – Cynigo Jul 10 '17 at 19:37
  • It doesn't.. `var arr = [1, 4, 10]; if(Math.min(...arr) > 1) { console.log('Must be greater than 1'); } undefined` – tholo Jul 10 '17 at 19:37
  • @Cynigo, I'm testing this in console right now. – tholo Jul 10 '17 at 19:38
  • You're probably not running in browser that supports ES6 spread syntax. Alternatively, you can use `Math.min.apply(null, arr);` and `Math.max.apply(null, arr);` – mhodges Jul 10 '17 at 19:38
  • your code works fine. https://jsfiddle.net/c9L9ae41/ – gpanagopoulos Jul 10 '17 at 19:38
  • Based on your `console.log` message, shouldn't it be `if(Math.min(...arr) <= 1) {`? – Joseph Marikle Jul 10 '17 at 19:39
  • Oh well, the function you're using doesn't return anything, hence the undefined. And since you're condition isn't met, it won't print anything either. Try replacing the `console.log('...');` with `return '...';` – Cynigo Jul 10 '17 at 19:39
  • @tholo Depending on what console you're using, it could be wrapping your code in an IIFE, and logging the return value (which in this case is undefined). – mhodges Jul 10 '17 at 19:39
  • @mhodges, Version 59.0.3071.115 (Official Build) (64-bit) - Chrome inspect, default. – tholo Jul 10 '17 at 19:40
  • Yeah.. sorry about that. – tholo Jul 10 '17 at 19:43
  • [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling Jul 10 '17 at 21:15
  • FWIW, you are not comparing 1 to the return value of `Math.min()`, not the spread "operator". – Felix Kling Jul 10 '17 at 21:38

1 Answers1

5

The logic is wrong.

var arr = [1, 4, 10];

if(Math.min(...arr) <= 1) {   
  console.log('Must be greater than 1'); 
}
Michał Pietraszko
  • 5,666
  • 3
  • 21
  • 27