panzerdp / dmitripavlutin.com-comments

7 stars 0 forks source link

javascript-math-max-infinity/ #123

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Why Math.max() Without Arguments Returns -Infinity

What is the reason that Math.max() utility function when being called without arguments returns -Infinity.

https://dmitripavlutin.com/javascript-math-max-infinity/

Learn-Deepak commented 3 years ago
const sum = (...numsList) => {
    if(numsList.length == 0){
        return 0;
    }
    let sum = 0;
    for(let i =0 ;i <numsList.length;i++){
       sum += numsList[i];
    }
    return sum;
}

console.log(sum(...[])); console.log(sum(...[1,1,1,1,1,1,9,6,5], 2,4,5,6,7,7, ...[]));

panzerdp commented 3 years ago

const sum = (...numsList) => { if(numsList.length == 0){ return 0; } let sum = 0; for(let i =0 ;i <numsList.length;i++){ sum += numsList[i]; } return sum; }

console.log(sum(...[])); console.log(sum(...[1,1,1,1,1,1,9,6,5], 2,4,5,6,7,7, ...[]));

Looks good. Thanks for sharing @Learn-Deepak!

Calanthe commented 3 years ago

Or with reduce:

const sum = (...numsList) => {
  const sum = numsList.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
  }, 0)

  return sum;
}
panzerdp commented 3 years ago

Or with reduce:

const sum = (...numsList) => {
  const sum = numsList.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
  }, 0)

  return sum;
}

Looks good @Calanthe! Thanks for sharing your solution.

aditya-padhi-kbl commented 3 years ago

Thank-you for this wonderful post. I learnt about Identity Element property & the reason why we get -Infinity in Math.max()