Thanks to visit codestin.com
Credit goes to coreui.io

How to use destructuring in JavaScript

Destructuring assignment provides a clean, concise way to extract values from arrays and objects into distinct variables. As the creator of CoreUI with extensive JavaScript experience since 2000, I’ve used destructuring extensively to simplify data extraction and variable assignment. From my expertise, the most powerful approach is using curly braces for objects and square brackets for arrays with optional default values. This ES6 feature significantly reduces code verbosity while improving readability and maintainability.

Use curly braces {} for object destructuring and square brackets [] for array destructuring.

const user = { name: 'John', age: 30, email: '[email protected]' }
const { name, age } = user

const numbers = [1, 2, 3, 4, 5]
const [first, second, ...rest] = numbers

Here const { name, age } = user extracts the name and age properties from the user object into separate variables. For arrays, const [first, second, ...rest] = numbers assigns the first element to first, the second to second, and collects remaining elements in the rest array using the spread operator. This pattern works with nested structures, allows default values, and supports renaming variables.

Best Practice Note:

This is the same approach we use in CoreUI components for extracting props and configuration options cleanly. Destructuring with default values like const { theme = 'light' } = props prevents undefined errors and provides fallback values.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Hide Scrollbar with CSS
How to Hide Scrollbar with CSS

CSS Selector for Parent Element
CSS Selector for Parent Element

JavaScript printf equivalent
JavaScript printf equivalent

Understanding Operator Precedence in JavaScript: Why Parentheses Matter with `??` and `?:`
Understanding Operator Precedence in JavaScript: Why Parentheses Matter with `??` and `?:`

Answers by CoreUI Core Team