ES6 Default Parameters in nested objects – JavaScript

ES6 allows you to set default parameters for nested objects using destructuring assignment. This feature helps handle cases where nested properties might be undefined or missing.

Syntax

function myFunction({ 
    outerKey: { 
        innerProperty = defaultValue, 
        anotherProperty = anotherDefault 
    } = {} 
} = {}) {
    // Function body
}

Example

Here's how to implement default parameters in nested objects:

function callBackFunctionDemo({ cl: { callFunctionName = "callBackFunction", values = 100 } = {} } = {}) {
    console.log(callFunctionName);
    console.log(values);
}

// This will print the default values
callBackFunctionDemo();

// This will print the given value for 'values', default for 'callFunctionName'
callBackFunctionDemo({ cl: { values: 500 } });

// This will use both custom values
callBackFunctionDemo({ cl: { callFunctionName: "customFunction", values: 750 } });
callBackFunction
100
callBackFunction
500
customFunction
750

How It Works

The destructuring pattern has three levels of defaults:

  • = {} at the end: Provides empty object if no argument is passed
  • = {} after the colon: Provides empty object if the outer property is missing
  • = defaultValue for each property: Provides default values for individual nested properties

Common Use Cases

// Configuration object with nested defaults
function setupUser({ 
    profile: { 
        name = "Anonymous", 
        age = 18, 
        location = "Unknown" 
    } = {},
    settings: { 
        theme = "dark", 
        notifications = true 
    } = {}
} = {}) {
    console.log(`User: ${name}, Age: ${age}, Location: ${location}`);
    console.log(`Theme: ${theme}, Notifications: ${notifications}`);
}

// Partial configuration
setupUser({ profile: { name: "John" } });

// No configuration
setupUser();
User: John, Age: 18, Location: Unknown
Theme: dark, Notifications: true
User: Anonymous, Age: 18, Location: Unknown
Theme: dark, Notifications: true

Conclusion

ES6 default parameters in nested objects provide a robust way to handle optional configuration objects. This pattern ensures your functions work gracefully even when nested properties are missing or undefined.

Updated on: 2026-03-15T23:19:00+05:30

619 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements