I'm following a project already created, and I ran across this notation in a Vue project with Vuex:
const { state = {} } = this.$store;
const { orders = {} } = state;
It seems to be defining a local object named state that is set equal to the value of the Vuex store... and then setting that equal to another object called "orders" but I'm a little lost on the notation itself. namely what this indicates:
{ variable = {} } = anotherObj
and also what this notation is called if it exists. (so that I can google it and figure out how it handles deep cloning, etc since it seems to be a way to clone objects.)... or maybe it's something particular to vuex?
This:
const { state = {} } = this.$store;
is destructuring assignment with a default value if the source (this.$store
) either doesn't have the property state
or has it but with the value undefined
. The result will be that state
will have the value of this.$store.state
if that property exists and doesn't have the value undefined
, or will have a new blank object if the property doesn't exist or has the value undefined
.
Example (using a string instead of an object, but it's the same principal):
const obj1 = {};
const { a = "default" } = obj1;
console.log(a); // "default"
const obj2 = {
b: "value from obj2"
};
const { b = "default" } = obj2;
console.log(b); // "value from obj2"