Why does this line doesnt work
x > highNum ? highNum = x : y > highNum ? highNum = y : highNum = highNum
In this case this line is in a loop and x and y is different everytime. I tried to find the highest number at the end and thought this would work. In my mind this reads as: If x is higher than high num highnum should get assigned the value of x if not. is y bigger? if yes y should be the new highnum. if not. dont change high num
Yes, they are.
Yes, but you should be concerned about readability too. You code does exactly what you are expecting it to do, but other devs (and maybe you in the future), could have a problem understanding that, so I'd strongly advice you to never use nested ternary operators, and only use them when it makes more sense then a simple if else statement. And if even after all this you still wanna use it, at least add a comment explaining what it does. ex:
let highNum
for(let line of lines){
const {x, y} = line;
// use bubble sort to find the highest number
x > highNum ? highNum = x : y > highNum ? highNum = y : highNum = highNum
}
edit: Also, this is also not correctly finding the highest number, as said by "trincot"
There is a potential high value that you could miss: when x > highNum, but also y > x, you will not see that y is really the highest, as the expression will already have decided that highNum should get the value of x.
You can do this quite simple with Math.max:
highNum = Math.max(x, y, highNum);
Yes, but you'll require brackets, mostly for readability:
(x > highNum) ? (highNum = x) : ((y > highNum) ? (highNum = y) : (highNum = highNum));
In your case, it seems you're better off splitting it into multiple statements to prevent confusion:
if (x > highNum) {
highNum = x;
} else if (y > highNum) {
highNum = y;
}
although that doesn't fit in a single expression, but perhaps that's a sign of your code getting a bit too complex/unreadable.
If you're solely looking for the highest number, perhaps Math.max is all you need, i.e. Math.max(x, y, highNum).