jeudi 20 février 2020

How does the ternary operator compares characters and numbers in JavaScript?

I had to find maximum in array so I wrote a function which used for loop while also using ternary operator and I noticed that just reversing the direction of loop changes the output plus the output is also different if I use if-else. Moreover, changing the position of 'a' in the array also changes the output.

const array2 = ['a', 3, 4, 2];

function biggestNumberInArray(arr) {
    let max=0;
    for (let i = 0; i < arr.length; i++) {
      max = max>arr[i]?max:arr[i];
    }
    return max;
}

function biggestNumberInArray2(arr) {
    let max=0;
    for (let i = arr.length - 1; i >= 0; i--) {
      max = max>arr[i]?max:arr[i];
    }
    return max;
}

console.log(biggestNumberInArray(array2));
console.log(biggestNumberInArray2(array2));

When running the first function output is 4

When running the second function output is 'a'

Aucun commentaire:

Enregistrer un commentaire