I would like to do a reassignment of a class variable in Javascript (or Typescript) using a ternary operator. The reassignment of this.foo depends on the current value of this.foo which I can update with the following:
setFoo = () => {
this.foo = this.foo ? "" : "foo";
}
However, I am wondering if I can do reassignment of this.foo without writing this.foo twice. This would be helpful because I am trying to dynamically update classes on an Angular component (written in Typescript).
I would like to be able to write something like the following which makes use of truthy/falsy values. If this.foo is truthy, then "" is assigned; otherwise, "foo" is assigned:
setFoo = () => {
this.foo =? "" : "foo";
}
I have tried searching for similar questions but could not find an answer. My initial thought was to use the ??= operator in Typescript 4.0 but I do not think it will work. Perhaps my ideal solution does not exist because it could be a bad programming habit. Thanks
this.foo = this.foo || ""andthis.foo = this.foo && "". That does not quite fit your need, but still is shorter.const. Don't minify your developement code, let a minifier do that when you're releasing the code to production.this.xs being redundant in that specific syntax, as there are two operators, and both of the operators need their operands. The case just happens to use the same variable in the operands of both of the operators. If the case wasconst x = (y) ? 1 : 2;, you wouldn't think1was redundant. For what you're after, we'd need a brand new "check&assign" operator ...