Destructuring with Defaults
Destructuring with Defaults & Safe Navigation in JS/TS
The TypeScript/JavaScript line const { theme = "light" } = profile?.preferences ?? {};
is a concise and robust way to extract a potentially nested property (theme
) while providing a default value ("light"
) if any part of the access path is null
or undefined
, or if the property itself is undefined
.
The Code Snippet
const { theme = "light" } = profile?.preferences ?? {};
Key Operators Involved
Operator | Syntax Example | In This Snippet | Purpose |
---|---|---|---|
Optional Chaining | obj?.prop | profile?.preferences | Safely accesses preferences . If profile is null or undefined , it evaluates to undefined without error. |
Nullish Coalescing Operator | value ?? defaultValue | ... ?? {} | If profile?.preferences is null or undefined , it provides an empty object {} as a fallback. Otherwise, it uses the value of profile?.preferences . |
Object Destructuring with Default Value | { prop = defaultValue } = obj | { theme = "light" } = ... | Extracts theme from the resulting object. If theme is undefined (or not present), it assigns "light" to the theme variable. |
How It Works Step-by-Step
profile?.preferences
:- Evaluates
profile
. Ifprofile
isnull
orundefined
, this entire expression short-circuits toundefined
. - If
profile
exists, it then attempts to accessprofile.preferences
.
- Evaluates
... ?? {}
:- The result from step 1 (either
profile.preferences
orundefined
) is checked. - If it's
null
orundefined
, the expression evaluates to the right-hand operand: an empty object{}
. - Otherwise (if
profile.preferences
had a value), it evaluates to that value.
- The result from step 1 (either
const { theme = "light" } = ...
:- Object destructuring is performed on the result of step 2 (which is guaranteed to be an object, either
profile.preferences
or{}
). - It attempts to find a property named
theme
in this object. - If
theme
exists and has a value, that value is assigned to the newtheme
constant. - If
theme
isundefined
(e.g., the property doesn't exist, or the object was{}
from step 2), the default value"light"
is assigned to thetheme
constant.
- Object destructuring is performed on the result of step 2 (which is guaranteed to be an object, either
This sequence ensures that theme
will always be initialized, preventing runtime errors from accessing properties on null
or undefined
objects.
Runnable Example
You can run this JavaScript code in a Node.js environment or a browser's developer console.
// Helper function to demonstrate the logic
function getProfileTheme(profile) {
const { theme = "light" } = profile?.preferences ?? {};
return theme;
}
console.log("--- Testing with different profile objects ---");
// Case 1: profile is undefined
let profile1;
console.log("Profile: undefined", "=> theme:", getProfileTheme(profile1)); // Expected: light
// Case 2: profile is null
const profile2 = null;
console.log("Profile: null", "=> theme:", getProfileTheme(profile2)); // Expected: light
// Case 3: profile exists, but preferences is undefined
const profile3 = {};
console.log("Profile: {}", "=> theme:", getProfileTheme(profile3)); // Expected: light
// Case 4: profile exists, preferences is null
const profile4 = { preferences: null };
console.log("Profile: { preferences: null }", "=> theme:", getProfileTheme(profile4)); // Expected: light
// Case 5: profile and preferences exist, but theme is undefined in preferences
const profile5 = { preferences: {} };
console.log("Profile: { preferences: {} }", "=> theme:", getProfileTheme(profile5)); // Expected: light
// Case 6: profile, preferences, and theme all exist
const profile6 = { preferences: { theme: "dark" } };
console.log("Profile: { preferences: { theme: 'dark' } }", "=> theme:", getProfileTheme(profile6)); // Expected: dark
// Case 7: profile, preferences exist, theme is explicitly set to another value
const profile7 = { preferences: { theme: "blue" } };
console.log("Profile: { preferences: { theme: 'blue' } }", "=> theme:", getProfileTheme(profile7)); // Expected: blue
To run:
- Save the code above as
example.js
. - Open your terminal or command prompt.
- Navigate to the directory where you saved the file.
- Run the command:
node example.js
You will see the output for each case, demonstrating how the theme
variable is correctly assigned "light"
or the value from profile.preferences.theme
.