nguyencuc2486
nguyencuc2486

Reputation: 57

problem with a very simple logical javascript program

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.

Upvotes: 2

Views: 78

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

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'));

Upvotes: 2

Related Questions