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

OperatorSyntax ExampleIn This SnippetPurpose
Optional Chainingobj?.propprofile?.preferencesSafely accesses preferences. If profile is null or undefined, it evaluates to undefined without error.
Nullish Coalescing Operatorvalue ?? 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

  1. profile?.preferences:
    • Evaluates profile. If profile is null or undefined, this entire expression short-circuits to undefined.
    • If profile exists, it then attempts to access profile.preferences.
  2. ... ?? {}:
    • The result from step 1 (either profile.preferences or undefined) is checked.
    • If it's null or undefined, the expression evaluates to the right-hand operand: an empty object {}.
    • Otherwise (if profile.preferences had a value), it evaluates to that value.
  3. 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 new theme constant.
    • If theme is undefined (e.g., the property doesn't exist, or the object was {} from step 2), the default value "light" is assigned to the theme constant.

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:

  1. Save the code above as example.js.
  2. Open your terminal or command prompt.
  3. Navigate to the directory where you saved the file.
  4. 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.