First of all, you can use the OR operand. It's idiomatic to mean "either get the value of a variable or a fallback value, if falsey"
assignment = someVariable || "fallback value"
Since you're checking this.state.data
every time, it's better to either check it once
const data = this.state.data || {}
and then use that
var assigned = data.assigned || 1,
delivered = data.delivered || 1,
unassigned = data.unassigned || 1,
pending = data.pending || 1,
total = data.total || 1,
failed = data.failed || 1;
This will leave this.state.data
untouched, you are just working with a different variable called data
.
Alternatively, you can directly check and possibly initialise this.state.data
, assuming that doesn't lead to problems with any other potential initialisation.
this.state.data = this.state.data || {}
and then you can check var assigned = this.state.data.assigned || 1
and so on.
Note that this style will give you the fallback if the current value is falsey. This includes an empty string or the number zero. If those are valid values, then you should not be using the OR operator to get them. For example, with this.state.data.failed = 0
the expression failed = this.state.data.failed || 1
will give you 1
. In that case, you might need to write a custom function to get the value or get a default value. If you have Lodash, you can use _.get()
for that purpose.
If you are using ES6, then this can be drastically shortened using a destructuring assignment with default values
const data = { assigned: 5, delivered: 10, total: 42 };
let {
assigned = 1,
delivered = 1,
unassigned = 1,
pending = 1,
total = 1,
failed = 1
} = data;
console.log("assigned", assigned);
console.log("delivered", delivered);
console.log("unassigned", unassigned);
console.log("pending", pending);
console.log("total", total);
console.log("failed", failed);
state
values come from and how they are used. \$\endgroup\$ – 200_success Feb 6 '19 at 18:53