Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript console -infinity, what does it mean?

I´m learning javascript ES6 and I just spotted with -infinity on my console when I run this code:

let numeros = [1, 5, 10, 20, 100, 234];
let max = Math.max.apply(numeros);
console.log(max);

What does it mean?

Regards

like image 498
Jmainol Avatar asked Mar 19 '19 16:03

Jmainol


2 Answers

The first argument of Function#apply is thisArg and you are just passing the thisArg as the array that means it's calling Math#max without any argument.

As per MDN docs :

If no arguments are given, the result is -Infinity.

In order to fix your problem set Math or null as thisArg.

let max= Math.max.apply(Math, numeros );

let numeros= [1,5,10,20,100,234];
    let max= Math.max.apply(Math, numeros );
    
    console.log( max );

As @FelixKling suggested, ES6 onwards you can use spread syntax to supply arguments.

Math.max(...numeros)

let numeros = [1, 5, 10, 20, 100, 234];
let max = Math.max(...numeros);

console.log(max);
like image 171
Pranav C Balan Avatar answered Sep 22 '22 03:09

Pranav C Balan


Use an ES6 Spread instead:

let numeros = [1, 5, 10, 20, 100, 234];
let max = Math.max(...numeros);
console.log(max);

As @Pranav C Balan already mentioned, -Infinity is what Math.max() is supposed to return (defined by spec) if no arguments are given:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max#Description

like image 24
NullDev Avatar answered Sep 18 '22 03:09

NullDev