Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is it possible to write a whole method that returns a value in ternary operator?

Is it possible to do this kind of code in the ternary operator in javascript? If yes, I think I’m doing it wrong, when I tried the code below I wrote it just return the whole function(){} method

  let sumtotal = products.length > 1 ? function(){
    let total = 0;
    for(const { price, quantity } of products) {
      total += (price * quantity);
    }
    return parseFloat(total).toFixed(2);
  } : function() {
    let total = (products[0].price * products.quantity);
    return parseFloat (total).toFixed(2);
  };

I was hoping that this would return an actual value like the output would be an Integer or float.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

"I was hoping that this would return an actual value like the output would be an Integer or float."

You can wrap your function definition in parenthesis and call it with () immediately after. An IIFE. You already have return so you are good on that part.

WITH CHANGES:

  let sumtotal = products.length > 1 ? (function(){
    let total = 0;
    for(const { price, quantity } of products) {
      total += (price * quantity);
    }
    return parseFloat(total).toFixed(2);
  })() : (function() {
    let total = (products[0].price * products.quantity);
    return parseFloat (total).toFixed(2);
  })();

With the IIFEs in place, the functions will run where they are. I haven’t checked any other parts of your code, so this solution is just for the "return an actual value like the output would be an Integer or float" part.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading