Just ran across this today (4 Cool Modern JavaScript Features Most Developers Don’t Know About | by fatfish | Nov, 2022 | JavaScript in Plain English) and thought "Hey, that might make some things a tad better in my Retool apps!"
The Logical OR Assignment (x ||= y
) operator only assigns if x is falsy.
A general example:
const obj = {
name: '',
age: 0
}
obj.name ||= 'fatfish'
obj.age ||= 100
console.log(obj.name, obj.age) // fatfish 100
As you can see, my friends, the assignment succeeds when the value of x is a false value.
Now how can we use it in Retool? To replace any situation where you are checking for an empty or falsy value, something like this:
{{txtName.value === '' ? "Not given" : txtName.value}}
or god forbid {{txtName.value === '' || txtName.value === null ? "Not given" : txtName.value}}
Scenario 1.
You have an update (or insert) query where you want to set a default if a component's value is empty:
This will set the default_public_notes
field to txtJobNewPublicNotes.value
if not blank and "Public Notes"
otherwise. Note that Retool's linter is showing an error in the code. It does still work despite that.
Scenario 2.
Set default value on query when additionalScope is not passed. Useful for default values and for debugging queries that need scope passed.
// JSQuery1
sqlQuery1.trigger({additionalScope: {username: "Brad"}})
-- sqlQuery1
Update users set name = {{username ||= 'Not Given'}}
Now if you want to check for null or undefined, but an empty string is an acceptable value, the the Nullish Coalescing Assignment ( x &&= y
) instead.
These are the use cases off the top of my head, I am sure there are a few others. Feel free to add your own use cases.