0

I use a ternary expression like this all the time, but I don't like the null in it. Is there a terser way to do this?

var_1 === 'yes' ? var_2=true : null;

This is a simplified version of what it is I am doing. I just want to check if something is true/false then do something otherwise do nothing(so I put null in). Is there a better way to do this?

cpplearner
  • 13,776
  • 2
  • 47
  • 72
Tim.Willis
  • 307
  • 2
  • 10

5 Answers5

1

The simplest way is to use var_2 = var_1 === 'yes'; as it works for all type like yes, undefined, null, '' and 0.

//when var_1 is 'yes'
var var_1 = 'yes';
var var_2 = var_1 === 'yes';
console.log(var_2);

//when undefined
var_1 = undefined;
var_2 = var_1 === 'yes';
console.log(var_2);

//when null
var_1 = null;
var_2 = var_1 === 'yes';
console.log(var_2);

//when blank
var_1 = '';
var_2 = var_1 === 'yes';
console.log(var_2);

//when 0
var_1 = 0;
var_2 = var_1 === 'yes';
console.log(var_2);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • 1
    but `var_2` gets a new value if the condition is `false`, which shouldn't. – Nina Scholz Aug 21 '18 at 14:27
  • @NinaScholz yes it does and I believe that should still be fine if OP want to use that value further as `null` and `false` can be used interchangeably – Ankit Agarwal Aug 21 '18 at 14:29
  • 1
    op is takling about `null` as value for the third part ternary, not as value for `var_2`, as i understand the question. for me, it looks like, if the condition is false, then the variable `var_2` should stay unchanged. – Nina Scholz Aug 21 '18 at 14:31
  • @NinaScholz I partially agree with you. Based on what OP has in question the intention seem to change the value of `var_2`. Let's wait for the input of OP. – Ankit Agarwal Aug 21 '18 at 14:40
0

Can var_2 be false? If so:

var_2 = var_1 === "yes";
TLP
  • 1,262
  • 1
  • 8
  • 20
0

Unlucky, there is no something like this, but maybe something like this will work for you:

var1 === 'yes' && var_2 = true

If argument before && is true than argument after && is also called and executed, otherwise only argument before is called and executed.

It is not clean way, but I sometimes use it.

ulou
  • 5,542
  • 5
  • 37
  • 47
0

I think you mean:

var_2 = var_1 === 'yes' ? true : null

You can also use the syntax

var_2 = var_1 === 'yes' && true

will set var_2 = true if var_1 = 'yes' otherwise var_2 = false

nbwoodward
  • 2,816
  • 1
  • 16
  • 24
0

The most correct way would be to check the condition and take that true result or if false use the original value as default for assignment.

That means the original value stays if the condition is false.

var2 = var1 === 'yes' || var2;
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392