Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 698
James Avatar asked Jan 02 '23 14:01

James


1 Answers

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 ); 
like image 113
Paul Avatar answered Jan 04 '23 04:01

Paul