problem with a very simple logical javascript program

Viewed 51

I am trying to solve a very simple exercise, they gave me 2 variables a and b, if a is falsy so we will assign b to result.

We must not use the If statement and the ternary operator.

Here is the suggestions they gave me :

function run(a, b) {
let result

...

return result
}

Could you please give me some ideas ? Thank you very much for your time.

1 Answers

Use the logical OR operator:

const result = a || b;

JavaScript logical operators use short-circuit evaluation, so b will only be evaluated if a is falsy.


In a snippet:

function run(a, b) {
  return a || b;
}

console.log(run('a', 'b'));
console.log(run('', 'b'));
console.log(run(0, 'b'));

Related