0

Is there a one line way of doing a if statement that only fires once with a boolean?

var boolean;    
if (!boolean) {
        function doSomething();
        boolean = true;
}

Something in the lines of this.

  • 1
    why do you want to write in one line? – Yousaf May 11 '21 at 12:25
  • @RBarryYoung My good man, https://stackoverflow.com/questions/21194934/how-to-create-a-directory-if-it-doesnt-exist-using-node-js#comment110333161_48436466 – Robyn May 11 '21 at 12:26
  • 2
    Code does not make any sense, why is there `function`? – epascarello May 11 '21 at 12:26
  • It can be converted to a single line - just remove anything except `function doSomething();` and you're just left with the syntax error. – VLAZ May 11 '21 at 12:26
  • 1
    `function doSomething();` is invalid. Do you want to declare a `doSomething` function or execute it? – adiga May 11 '21 at 12:26
  • 1
    You might want to provide more context, e.g. how `boolean` is supposed to be read. It's useless in this tiny example. – Felix Kling May 11 '21 at 12:33

2 Answers2

2

You could take the logical OR assignment ||= with a comma operator.

boolean ||= (doSomething(), true);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

It does not make much sense to do it as one line since the code is clear the way you have it written (minus your syntax error), but it can be done

function test(myBool) {
  function doSomething () { console.log('run'); }
  myBool = myBool || doSomething() || true;
  console.log(myBool);
}

test(false);
test(true);

or if doSomething returns a true boolean or truthy value

function test(myBool) {
  function doSomething () { console.log('run'); return true; }
  myBool = myBool || doSomething();
  console.log(myBool);
}

test(false);
test(true);
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • if `doSomething` returns a falsy value like `NaN`, it will set that value to `myBool` – adiga May 11 '21 at 12:35
  • 1
    I think `myBool = myBool || !doSomething() || true` ensures it always returns `true` irrespective of what `doSomething` returns – adiga May 11 '21 at 12:44