Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way in ES6 to assign a constant conditionally?

Tags:

ecmascript-6

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?

like image 569
Midiparse Avatar asked Nov 10 '15 11:11

Midiparse


People also ask

What does const {} mean in JS?

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

How do you assign a const in JavaScript?

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.

How do you set a variable based on a condition?

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

What is const in ES6?

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.


1 Answers

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.

like image 186
Leonid Beschastny Avatar answered Sep 21 '22 01:09

Leonid Beschastny