DEV Community

Cover image for Destructuring In Javascript
Anoop Rajoriya
Anoop Rajoriya

Posted on

Destructuring In Javascript

Destructuring in javascript is the one of the feature which reduce a code verbosity and speed-up writing array or objects data manipulation. Here i'm showing you how can you use it with arrya and objects, and seeing some features and advantages of destructuring.

Meaning of destructuring

It a special syntax for unpacking array items or object property access. it provide a concise and rcodable way to reduce code verbosity. It does not modify original data

Destructuring array

To destructure array you need to use [] square bracket in left hand side and put array ref in right hand side from which items going to destructure in bracket all item are available based on indexing, you can catch these item in variables.

Syntax :

const items = ["apple", "ball", "cat"]
const [first, second, thired] = items

console.log(first)      // apple
console.log(second)     // ball
console.log(thired)     // cat
Enter fullscreen mode Exit fullscreen mode

if you want to skipp some values which not used in you code it can be done by just using some extras commas:

const [first, , thired] = items

console.log(first) // apple
console.log(thired) // cat
Enter fullscreen mode Exit fullscreen mode

Destructuring object

Object destructuring same as array destructuring only differences is instead of square brackets we use curly brackets and catches all propertie in these brackets by their actual keys name at left hand side. In array we need to ensure sequances must be same and in object we need to ensure properties name will same.

Syntax :

const user = {name: "anoop", age: 21}
const {name, age} = user

console.log(name)   // anoop
console.log(age)    // age
Enter fullscreen mode Exit fullscreen mode

In that if you need to change the properties name alias you can do it by simple using this syntax:

const {name: full_name} = user

console.log(full_name) // anoop
Enter fullscreen mode Exit fullscreen mode

Default values

Default values used as fallback values for destructured property or elements those are not exist or explicitly set to undefined. To assign a default value (=) operator used within a destructuring pattern.

1. In object destructuring

You can set any destructured property default value. which used when property values not exist or set to underfined.

const settings = {}
const {theme = "dark"} = settings

console.log(theme) // dark
Enter fullscreen mode Exit fullscreen mode

2. In array destructuring

Default value are assigned to destructured elements variable when corresponding index not exist or element is undefined.

const user = ["anoop"]
const [name, role="user"] = user

console.log(name, role) // anoop user
Enter fullscreen mode Exit fullscreen mode

Behavior which should known

  • Default values only used when destructuring values are undefined. Other falsy values like false, null, 0 and empty string tread as valid values.

  • If function used as default value then it only evaluated when need if value existed it will not evaluated.

Benefits of destructuring:

  1. Improve code readability conciseness : it reduce repeatative code like instead of writing object.Property and array[index]can directly extract vlaues using destructuring pattern. Properties or clements extraction which take multiple line of code can done within a single line. Destructuring item at top of function or black explicity show which piec of data are being used.

  2. Dowerful data manipulation : using destructuring perform some powerful data manupulation operations like swapping values without needing thired value. Addign defoult or fullback value if elements or properties are missing or undefined. Making alies can easily rename variables name to reduce naming conflicts. If you want to skip un-wanted variables or items in array or objects can do with only few extra commas.

Summry

  • syntax of unpacking values from arrya or objects
  • [first, second] = items destructuring arrya elements
  • [first, , thired] = items skipping arrya elements
  • {name, role} = user destructuring objects properties
  • {name: full_name, role: user_role} = user making alies
  • [name, role="user"] defaults values
  • fallback applies only undefined values & evaluated only when needed

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

"Array" style destructuring is not just for arrays - it is for ANY iterable. Strings - for example:

const [first, second, third] = "dog"
console.log(first, second, third) // 'd', 'o', 'g'
Enter fullscreen mode Exit fullscreen mode