I would like to assign to my const validation
a value based on a condition.
If this.showRequired() == true
Then it should be 'required'
Else if this.showError() == true
Then it should be 'error'
.
I know of course that I could extract it to a function, or cascade ternary operators, but the first seems code bloat, the latter ugly.
Is there a better way to do it? If-else expressions maybe?
In JavaScript, `const` means that the identifier can't be reassigned. (Not to be confused with immutable values. Unlike true immutable datatypes such as those produced by Immutable. js and Mori, a `const` object can have properties mutated.)
It can be assign on the variable on declaration line. Primitive value. The property of a const object can be change but it cannot be change to reference to the new object. The values inside the const array can be change, it can add new items to const arrays but it cannot reference to a new array.
The conditional ternary operator in JavaScript assigns a value to a variable based on some condition and is the only JavaScript operator that takes three operands. result = 'somethingelse'; The ternary operator shortens this if/else statement into a single statement: result = (condition) ?
ES6 introduced the const keyword, which is used to define a new variable in JavaScript. Generally, the var keyword is used to declare a JavaScript variable. Const is another keyword to declare a variable when you do not want to change the value of that variable for the whole program.
Cascading ternary operator looks fine for me:
const validation = this.showRequired() ? 'required' : this.showError() ? 'error' : null
If you think this line is too long, you could split it:
const validation = this.showRequired() ? 'required'
: this.showError() ? 'error'
: null
Or you could use &&
and ||
instead:
const validation = (this.showRequired() && 'required') ||
(this.showError() && 'error')
As for extacting this code into a separate function, you could always use an inline function instead of creating yet another class method:
const validation = (() => {
if (this.showRequired()) {
return 'required'
} else if (this.showError()) {
return 'error'
}
})()
But ternary operator looks better anyway, especially if it's split into several lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With