0

I have a question about a technicality in JS. Is it possible to use the destructuring assignment to hold both true and false options of a ternary operator? (check comment in the code)

const firstOne = {
    fullName: `Mark Miller`,
    weight: 78,
    height: 1.69,
    calcBMI: function () {
        this.BMI = this.weight / (this.height ** 2);
        return this.BMI;
    }
}
const secondOne = {
    fullName: `John Smith`,
    weight: 92,
    height: 1.95,
    calcBMI: function () {
        this.BMI = this.weight / (this.height ** 2);
        return this.BMI;
    }
}
const [winner, looser] = [firstOne.BMI > secondOne.BMI ? firstOne : secondOne, firstOne.BMI > secondOne.BMI ? secondOne : firstOne]; // is there a better way to do this?
console.log(`${winner.fullName} has the higher BMI(${winner.calcBMI()}) 
while ${looser.fullName} has a BMI of ${looser.calcBMI()} `);
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
  • No, it is not possible. The result of a `? :` operation is one side of the `:` or the other. Only one is evaluated. – Pointy Jul 02 '22 at 15:39
  • `const [winner, looser] = (firstOne.BMI > secondOne.BMI) ? [firstOne, secondOne] : [secondOne, firstOne];` <--- please try this and share your feedback. Or, perhaps it should be: `const [winner, looser] = (firstOne.calcBMI() > secondOne.calcBMI()) ? [firstOne, secondOne] : [secondOne, firstOne];` – jsN00b Jul 02 '22 at 15:39
  • Basically, you are asking for array `[firstOne, secondOne]` to be sorted by property `BMI`, descending. – Ruud Helderman Jul 02 '22 at 15:40
  • Thanks a lot, I didn't think about using destructuring times 2 @JsN00b – FullMetal Jesus Jul 02 '22 at 16:20
  • @RuudHelderman I'm not sure that in my code can be considered as an array, but an array solution is also pretty neat too :). I guess it would be something like ```const bmiArr =[firstOne.calcBMI, secondOne.calcBMI].sort( (a,b)=>return a.BMI>b.BMI? a : b )``` – FullMetal Jesus Jul 02 '22 at 16:39
  • @FullMetalJesus The idea is: `const [winner, looser] = [firstOne, secondOne].sort((a, b) => b.BMI - a.BMI)` With zero effort, it scales to 3 or more candidates. – Ruud Helderman Jul 02 '22 at 19:38
  • @RuudHelderman Very clear, thanks alot – FullMetal Jesus Jul 02 '22 at 19:49

0 Answers0