I want to define a base object called defaultsettings with two nested object properties: ajaxsettings and uisettings. I know I can do it like this:
var defaultsettings = new Object();
var ajaxsettings = new Object();
defaultsettings.ajaxsettings = ajaxsettings;
// and so on...
But I’m wondering what the more correct or modern way is to declare nested objects directly, for example:
var defaultsettings = {
ajaxsettings: { ... },
uisettings: { ... }
};
What’s the recommended approach for creating and organizing JavaScript nested objects?
From my experience, the modern, cleanest way to create JavaScript nested objects is indeed by using object literals right inside the main object declaration, just like your second example. This keeps everything neat and easy to read:
const defaultsettings = {
ajaxsettings: {
timeout: 5000,
method: 'GET'
},
uisettings: {
theme: 'dark',
language: 'en'
}
};
This method is widely recommended because it avoids unnecessary verbosity, makes the structure immediately clear, and fits naturally with modern JavaScript best practices.
Building on that, while using new Object()
or creating empty objects and then assigning them is valid, it’s generally seen as old-fashioned and less intuitive when dealing with JavaScript nested objects. Object literals ({}
) are preferred because they’re concise and make your code more readable. Plus, defining nested objects directly inside the parent object keeps your code compact and prevents you from scattering declarations all over the place. For example:
const defaultsettings = {
ajaxsettings: {},
uisettings: {}
};
You can always add properties later, but this keeps your initial declaration simple and focused.
That said, when your JavaScript nested objects grow more complex or the config becomes sizable, I find it’s a good idea to split parts into separate constants or even modules. This improves readability and maintainability, especially in bigger projects where you might want to import or update specific settings independently. Like this:
const ajaxsettings = {
timeout: 3000,
cache: false
};
const uisettings = {
theme: 'light',
fontSize: '14px'
};
const defaultsettings = {
ajaxsettings,
uisettings
};
This approach balances clarity and modularity, helping your project scale without turning your main object into an overwhelming block of code.