Course contentsShow
← JavaScript
Lesson 934 of 2,72321. DestructuringFree lesson

Combining Renaming and Defaults

Use both variable renaming and default values together in destructuring patterns.

Combining Renaming and Defaults

You'll learn how to use both variable renaming and default values in the same destructuring pattern for maximum flexibility.

The Power of Combining Features

So far, you've learned to rename variables during destructuring (using the colon syntax) and to provide default values (using the equals sign). The great news? You can use both together in the same destructuring operation!

This is incredibly useful when working with objects that might have missing properties and you want to use more descriptive variable names in your code.

How It Works

The syntax follows a specific order: originalProperty: newName = defaultValue

Think of it like this: "Take the property called originalProperty, rename it to newName, and if it doesn't exist, use defaultValue."

const settings = { theme: 'dark' };

// Rename 'theme' to 'appTheme', and provide defaults
const { theme: appTheme = 'light', lang: language = 'en' } = settings;

console.log(appTheme);  // 'dark' (exists, so uses actual value)
console.log(language);  // 'en' (missing, so uses default)

Practical Example

This pattern shines when dealing with configuration objects or API responses:

const userProfile = {
  nm: 'Alice',
  age: 30
  // note: 'loc' property is missing
};

const { nm: name = 'Guest', loc: location = 'Unknown' } = userProfile;

console.log(name);      // 'Alice'
console.log(location);  // 'Unknown'

You're simultaneously handling unclear property names (like nm) and missing data (like loc), making your code both readable and resilient.

Key Takeaway: Combine renaming and defaults with the pattern { oldName: newName = defaultValue } to handle unclear property names and missing values simultaneously in a single destructuring statement.