Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
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 products = [
  {
    price: 2.6,
    quantity: 5,
  },
  {
    price: 5.9,
    quantity: 5,
  },
  {
    price: 2.3,
    quantity: 5,
  },
  {
    price: 4.9,
    quantity: 5,
  }
];

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);
};

console.log(sumtotal);

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

"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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda