Is there an operator that would allow the following logic (on line 4) to be expressed more succinctly?
const query = succeed => (succeed? {value: 4} : undefined);
let value = 3;
for (let x of [true, false]) {
try { value = query(x).value; } catch {} // <-- Don´t assign if no .value
}
console.log(value);
The output is 4. If there is no .value field in the response, I want to keep the old value / don´t want the assignment to execute.
Notes:
- If
value = query(x)?.valuewere used, it would assignundefinedtovalue - There is also the
??=operator, however it isn´t useful here,value ??= ...would only assign ifvalueis currentlynull/undefined - In CoffeeScript,
value = query(x).value if query(x)?.value?achieves the desired behaviour withouttry/catch, although it's repetitive value = query(x)?.value ?? valueworks but isn't conditional assignment, the assignment still happens, if we were setting anObject's property the setter would be called unnecessarily. It is also repetitive- This logic cannot be abstracted into a function i.e.
value = smart(query(x), "value"), the assignment can´t be made conditional that way
Keywords?
null propagation, existence operator
if( obj?.nested?.property?.value )instead ofif( obj && obj.nested && obj.nested.property && obj.nested.property.value )var appConfig = loadConfig(config, process.env); connect(appConfig.database);toconnect(config). You can pass a much simpler object toconnectinstead of passing the wholeconfigobject, you can useconf.username,conf.passwordinstead of attempting something likeconfig[process.env]?.database?.username,config[process.env]?.database?.password. Reference: Law of Demeter.loadConfigin the example above), you can make assumptions about the existence of properties and skip null checking in countless areas of your app.