Search code examples
javascriptbooleanlogical-operatorsshort-circuiting

Prevent value of 0 evaluating to false when using logical OR


I am wondering if there was a way around this issue. I am currently storing a value in a variable like so:

Session['Score'] = 0; 

Later I have an assignment like so:

Score = Session['Score'] || 'not set';

The problem is, when Session['Score'] is set to 0 as above, JavaScript will interpret it as:

Score = false || 'not set';

which means Score will evaluate to 'not set' instead of 0!

How can I get around this issue?


Solution

  • You can do this with destructuring assignment:

    let { Score = 'not set' } = Session;
    

    If it's not set:

    const Session = { };
    let { Score = 'not set' } = Session;
    console.log( Score ); 

    If it is set to any value other than undefined, including falsy ones:

    const Session = { Score: 0 };
    let { Score = 'not set' } = Session;
    console.log( Score );