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

132
Vistas
Dynamic variables based on condition

I'm trying to make the property value of an object to be dynamic based on a given condition.

For example, the property value would become Red if the viewport width is <= 1280 , else it would be Yellow .

I'm trying to use the if...else statement but it shows an error: SyntaxError: missing ) after formal parameters.

const firstData = {
  if (document.documentElement.clientWidth <= 1280) {
    apple: 'Red'
  } else {
    apple: 'Yellow'
  }
};

// Or

const secondData = {
  apple: if (document.documentElement.clientWidth <= 1280) {
    return "Red"
  } else {
    return "Yellow"
  }
};

console.log(firstData, secondData);

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

0

Use a ternary operator to do it cleaner.

const data = {
  apple: document.documentElement.clientWidth <= 1280 ? "Red" : "Yellow",
};

console.log(data);

about 4 years ago · Juan Pablo Isaza Denunciar

0

If You want one line condition then above answer is best but with more conditions you can do something or define the function else where then run it

const obj = {
    apple: (() => {
        if (document.documentElement.clientWidth <= 1280) {
            return 'Red';
        } else {
            return 'Yellow';
        }
    })(),
};

or you can even define dynamic properties

const obj = {
    ...(() => {
        if (document.documentElement.clientWidth <= 1280) {
            return { color: 'Red' };
        } else {
            return { color1: 'Yellow' };
        }
    })(),
    color3: 'red',
};
console.log(obj);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can't use statement as object value. Instead of this you can use ternary operator.

const object = {
    apple: document.documentElement.clientWidth <= 1280 ? 'Red' : 'Yellow', 
}
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