64

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?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
RaviTeja
  • 988
  • 3
  • 13
  • 20
  • 3
    Doesn't the first limit `myVariable` to the scope it has been assigned in and can't be used outside of the `if` or the `else` it has been assigned in. – Tomaltach Oct 13 '17 at 09:59
  • 1
    `var` is funky in javascript and is scoped to the function (or global) not the block. That's another advantage of using `let` over `var`. – Jordan Soltman Jun 04 '19 at 01:27

15 Answers15

130

try this

var myVariable = (true condition) ? "true" : "false"
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
  • 4
    Is this different than the first way? Isn't it the same thing with different syntax? – Andy Groff Jun 07 '12 at 06:48
  • @Rajkumar, This is no different from the first. I actually want clarification about the over-riding thing. The second way is assigning a variable and then overriding it with something else. Is that a good way to do? – RaviTeja Jun 07 '12 at 08:13
  • 1
    yeah.. you can do that. whenever there is a default value.. .second way is good. In second way actually you are assigning a default value false and later on you are modifying it based on conditions. – dku.rajkumar Jun 07 '12 at 09:59
  • What if you have 3? Why no inline ifelse statement in the world? – gunslingor Aug 23 '22 at 19:43
33

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";
Kevin Ng
  • 2,146
  • 1
  • 13
  • 18
17

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.

Julian E.
  • 4,687
  • 6
  • 32
  • 49
Valentin
  • 2,772
  • 1
  • 27
  • 40
  • 1
    can anyone explain the PS added at the end? ...Why "learning purposes only" and not for use in production code? My guess is that it's unusual compare to other languages, so it'd maybe cause confusion. – C-Note187 Mar 28 '22 at 18:41
  • 1
    @C-Note187 I added the PS because while it's a concise way to do assignment, it also hard to understand what the code does on first glance. So if someone's doing code review or maybe finds this line of code during development, he's going to waste some time trying to understand it. In these cases it would be easier to just use if statements so that whoever is looking at the code can understand the logic quickly, with less mental overhead. – Valentin Apr 01 '22 at 09:20
  • 1
    oh, you are the best. I just wanted more than two on conditions and single ternary operator was not enough and I didn't want that long ifs or switch. – irakli2692 Jul 17 '23 at 18:38
11

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

var myVariable = (true) ? 'True' : 'False';
Joseph
  • 117,725
  • 30
  • 181
  • 234
9

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]
aris
  • 22,725
  • 1
  • 29
  • 33
7

Third way when you are storing only true false in variabel then use

 var myVariable =(condition_written_in_if);
6

Just for completion, there is another way in addition to all the others mentioned here, which is to use a lookup table.

Say you have many possible values, you could declaratively configure a Map instead of using an if, switch or ternary statement.

Object map = {
   key1: 'value1',
   key2: 'value2',
   keyX: 'valueX'
};

var myVariable = map[myInput];

This works even for booleans:

Object map = { true: 'value1', false: 'value2 };

var myVariable = map[myBoolean];

For booleans you would probably do it the 'normal' way though with logic operators specifically designed for that. Though sometimes it can be useful, such as:

  • portability: you can pass a map around
  • configurability: maybe the values come from a property file
  • readability: if you don't care it's a boolean or not, you just want to avoid conditional logic and reduce cognitive load that way

Note there is some overlap between the advantages using a lookup map and advantages of using a function variable (closure).

Benny Bottema
  • 11,111
  • 10
  • 71
  • 96
4

The first solution uses only one assignment instead of 1,5 by average in the second code snippet. On the other hand the first code snippet is less readable as people not familiar with JavaScript might not realize that the scope of a variable is not block oriented by function oriented - on other languages with C-like syntax myVariable would not be accessible outside if and else blocks.

In other words both solutions have disadvantages. What about ternary operator:

var myVariable = condition? 'True' : 'False';

or if you don't care about the camel-case (although I understand this is just an example, not a real code);

var myVariable = (!!condition).toString();
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

If you tired of ternary operator then use IIFE

Another way would be to use Immediately Invoked Function Expression. The good thing about it is that it can hold some logic and can be encapsulated from the outside world.

const direction = "n";

const directionFull= (() => {
    switch(direction ){
        case "n": return "north";
        case "s": return "south";
        case "w": return "west";
        case "e": return "east"; 
    }
})()

console.log(directionFull);
1

I would prefer 2nd option too, no technical reason but for the sake of easy to read code, readability is very important in code.

If you see the second option, from processing point of view only one check will ever be executed, saved some very minute processing time, so there is only one check in second case.

mprabhat
  • 20,107
  • 7
  • 46
  • 63
  • one technical reason:there will be only one condition check in second –  Jun 07 '12 at 06:47
0

It depends on the use for me. If I have code that I only want to run if true, but with no extra code for false, I'll use the second. If I want to execute some code on true, and different on false, I use the first. It all depends on use, but the general rule for me is to write once. Keep it clean, keep it simple, and keep it short

Gareth Parker
  • 5,012
  • 2
  • 18
  • 42
0

Maybe you simply need && operator to check if boolean is true, if it is, assing "myVariable" to true.

var myVariable = 'False';
true && myVariable = 'True';
Eric Valero
  • 540
  • 5
  • 8
0

If all you need to do is convert a boolean to a string, you should do so explicitly:

var myBool = true;
var myVariable = myBool.toString(); // 'true'
// '' + myBool, ''.concat(myBool), etc. also work

If it's important that the first letter be capitalized, as in your example, that is not difficult to do; see e.g. this answer.

Malcolm
  • 510
  • 3
  • 5
  • 19
0

Another approach with Map and Object: (Maps are more flexible with key types and Objects are more readable IMHO)

const condition_var = 'e'

const options1 = new Map([ ['n','north'],['s','south'],['e','east'],['w','west']])
const myVar1 = options1.get(condition_var) || null

const options2 = {n:'north', s:'south', e:'east', w:'west'}    
const myVar2 = options2[condition_var] || null

console.log(myVar1)
console.log(myVar2)
Cesar Morillas
  • 707
  • 5
  • 11
0

If what you're trying to do is set a value if it is not null/undefined, and otherwise use another value, you can use the nullish coalescing operator:

const thing = obj.field ?? otherVal;
jeffrey.d.m
  • 616
  • 8
  • 23