In my FAC (Friday Afternoon Contemplations) I will regularly try to address some problems that many of us have run into using Velo and/or Javascript. I’ll keep it as short as possible.
1)falsy and truthy
Many times I see people doing something like this in code:
let thisImage = thisQueryRow[i].image;
if (thisImage !=="" || thisImage !== null || thisImage!==undefined){ //do something}
But Javascript has this all built in. You can simply do:
if (thisImage){ //do something}
It’s called “thruthy/truthyness” and “falsy/falsyness” (ref : Falsy - MDN Web Docs Glossary: Definitions of Web-related terms | MDN} and it means that Javascript will do all those test for you (not empty, not null, not undefined, not non-a-number (Nan), whatever.
- tri-valued booleans (and how to not-not them)
So booleans can hold only two values, true or false, right? No. They can hold 3 (tri-valued): true, false and undefined. In code, you are the king, so you can prevent a boolean going ‘undefined’ by good declaration. But when working with wix-data, it can be trickier: when you define a boolean in a collection, then the “unchecked” state could mean 2 things: false or undefined. It will be false when, in Content Manager you expressly checked and unchecked it. But if you did nothing, it will be ‘undefined’. So how can that hurt you?
From my own experience, I once did this after retrieving data from a collection:
if (thisRow.boolIsRefundable === nextRow.boolIsRefundable) { //do something}
and the test did not work. On inspection (console.log is your friend), it turned out that one was ‘false’ and the other one ‘undefined’. So they are NOT equal, which they kind of should have been.
Now, you can go back to your collection in Content Manager and set all booleans explicitly to ‘false’, but that’s a lot of work and error prone: a new row might carry the same result. It’s better to solve it in code. Paste the following code into your editor and Preview it:
let boolTrue = true;
console.log("!!true=" + !!boolTrue);
let boolFalse = false;
console.log("!!false=" + !!boolFalse);
let boolUndef = undefined;
console.log("!!undefined=" + !!boolUndef);
You will see that by adding not-not, true will stay true, false will stay false, but undefined will become false! Exactly what we wanted.
So the test would now become:
if (!!thisRow.boolIsRefundable === !!nextRow.boolIsRefundable) { //do something}
and will work as expected, always.
Hope this is of help to some of you, have a nice weekend.
Next week: the danger of tying a checkbox to a collection-boolean