Best Way for Conditional Variable Assignment

Which is the better way for conditional variable assignment?

1st method

 if (true) {
   var myVariable = 'True';
 } else {
   var myVariable = 'False';
 }

2nd Method

 var myVariable = 'False';
 if (true) {
   myVariable = 'True';
 }

I actually prefer 2nd one without any specific technical reason. What do you guys think?


try this

var myVariable = (true condition) ? "true" : "false"

There are two methods I know of that you can declare a variable's value by conditions.

Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into one statement.

var a = (true)? "true" : "false";

Nesting example of method 1: Change variable A value to 0, 1, 2 and a negative value to see how the statement would produce the result.

var a = 1;
var b = a > 0? (a === 1? "A is 1" : "A is not 1") : (a === 0? "A is zero" : "A is negative");

Method 2: In this method, if the value of the left of the || is equal to zero, false, null, undefined, or an empty string, then the value on the right will be assigned to the variable. If the value on the left of the || does not equal to zero, false, null undefined, or an empty string, then the value on the left will be assigned to the variable.

Although the value on the left can be an undefined value for JS to evaluate the condition but the variable has to be declared otherwise an exception will be produced.

var a = 0;
var b = a || "Another value";

An alternative way of doing this is by leveraging the ability of logical operators to return a value.

let isAnimal = false;
let isPlant = true;

let thing = isAnimal && 'animal' || isPlant && 'plant' || 'something else';

console.log(thing);

In the code above when one of the flags is true isAnimal or isPlant, the string next to it is returned. This is because both && and || result in the value of one of their operands:

  • A && B returns the value A if A can be coerced into false; otherwise, it returns B.
  • A || B returns the value A if A can be coerced into true; otherwise, it returns B.

Answer inspired by this article: https://mariusschulz.com/blog/the-and-and-or-operators-in-javascript

PS: Should be used for learning purposes only. Don't make life harder for you and your coworkers by using this method in your production code.


You could do a ternary, which is a lot shorter (and no darn curly braces):

var myVariable = (true) ? 'True' : 'False';

Another cool thing is that you can do multiple assignment based on a conditional:

let [long_str, short_str] = a.length > b.length ? [a, b] : [b, a]