Home > Net >  Dynamic variables based on condition
Dynamic variables based on condition

Time:07-13

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

CodePudding user response:

Use a ternary operator to do it cleaner.

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

console.log(data);

CodePudding user response:

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

CodePudding user response:

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', 
}
  • Related