As explained in one of my posts in the Javascript series, you can use the optional chaining operator to simplify and avoid breaking code
So the below code:
๐ค๐ฐ๐ฏ๐ด๐ต ๐ถ๐ด๐ฆ๐ณ = {
๐ฏ๐ข๐ฎ๐ฆ: '๐๐ข๐ท๐ช๐ฅ'
};
๐ค๐ฐ๐ฏ๐ด๐ต ๐ด๐ต๐ณ๐ฆ๐ฆ๐ต๐๐ข๐ฎ๐ฆ = ๐ถ๐ด๐ฆ๐ณ.๐ญ๐ฐ๐ค๐ข๐ต๐ช๐ฐ๐ฏ && ๐ถ๐ด๐ฆ๐ณ.๐ญ๐ฐ๐ค๐ข๐ต๐ช๐ฐ๐ฏ.๐ด๐ต๐ณ๐ฆ๐ฆ๐ต && ๐ถ๐ด๐ฆ๐ณ.๐ญ๐ฐ๐ค๐ข๐ต๐ช๐ฐ๐ฏ.๐ด๐ต๐ณ๐ฆ๐ฆ๐ต.๐ฏ๐ข๐ฎ๐ฆ;
is same as:
๐ค๐ฐ๐ฏ๐ด๐ต ๐ถ๐ด๐ฆ๐ณ = {
๐ฏ๐ข๐ฎ๐ฆ: '๐๐ข๐ท๐ช๐ฅ'
};
๐ค๐ฐ๐ฏ๐ด๐ต ๐ด๐ต๐ณ๐ฆ๐ฆ๐ต๐๐ข๐ฎ๐ฆ = ๐ถ๐ด๐ฆ๐ณ.๐ญ๐ฐ๐ค๐ข๐ต๐ช๐ฐ๐ฏ?.๐ด๐ต๐ณ๐ฆ๐ฆ๐ต?.๐ฏ๐ข๐ฎ๐ฆ;
In the above code, ๐๐๐ฟ๐ฒ๐ฒ๐๐ก๐ฎ๐บ๐ฒ will be ๐๐ป๐ฑ๐ฒ๐ณ๐ถ๐ป๐ฒ๐ฑ as ๐๐๐ฟ๐ฒ๐ฒ๐ property does not exist on the user object.
This is because the optional chaining operator returns ๐๐ป๐ฑ๐ฒ๐ณ๐ถ๐ป๐ฒ๐ฑ if the property does not exist.
And destructuring on ๐๐ป๐ฑ๐ฒ๐ณ๐ถ๐ป๐ฒ๐ฑ will throw an error.
So If you're using destructuring along with the optional chaining operator, you will get an uncaught error If you try to use destructuring like this:
๐ช๐ง (๐ถ๐ด๐ฆ๐ณ.๐ฏ๐ข๐ฎ๐ฆ) {
๐ค๐ฐ๐ฏ๐ด๐ต { ๐ฏ๐ข๐ฎ๐ฆ, ๐ข๐ฅ๐ฅ๐ณ๐ฆ๐ด๐ด } = ๐ถ๐ด๐ฆ๐ณ.๐ญ๐ฐ๐ค๐ข๐ต๐ช๐ฐ๐ฏ?.๐ด๐ต๐ณ๐ฆ๐ฆ๐ต; // ๐๐ฃ๐๐๐ช๐๐๐ฉ ๐๐ฎ๐ฅ๐๐๐ง๐ง๐ค๐ง: ๐พ๐๐ฃ๐ฃ๐ค๐ฉ ๐๐๐จ๐ฉ๐ง๐ช๐๐ฉ๐ช๐ง๐ ๐ฅ๐ง๐ค๐ฅ๐๐ง๐ฉ๐ฎ '๐ฃ๐๐ข๐' ๐ค๐ ๐ช๐ฃ๐๐๐๐๐ฃ๐๐
}
To fix this, you need to assign an empty object all the time while destructuring like this:
๐ช๐ง (๐ถ๐ด๐ฆ๐ณ.๐ฏ๐ข๐ฎ๐ฆ) {
๐ค๐ฐ๐ฏ๐ด๐ต { ๐ฏ๐ข๐ฎ๐ฆ, ๐ข๐ฅ๐ฅ๐ณ๐ฆ๐ด๐ด } = ๐ถ๐ด๐ฆ๐ณ.๐ญ๐ฐ๐ค๐ข๐ต๐ช๐ฐ๐ฏ?.๐ด๐ต๐ณ๐ฆ๐ฆ๐ต || {}; // ๐ฌ๐ค๐ง๐ ๐จ ๐๐๐ฃ๐, ๐ฃ๐ค ๐๐ง๐ง๐ค๐ง
๐ค๐ฐ๐ฏ๐ด๐ฐ๐ญ๐ฆ.๐ญ๐ฐ๐จ(๐ฏ๐ข๐ฎ๐ฆ, ๐ข๐ฅ๐ฅ๐ณ๐ฆ๐ด๐ด); // ๐ถ๐ฏ๐ฅ๐ฆ๐ง๐ช๐ฏ๐ฆ๐ฅ ๐ถ๐ฏ๐ฅ๐ฆ๐ง๐ช๐ฏ๐ฆ๐ฅ
}
Top comments (0)