DEV Community

Cover image for Javascript ES6: Destructuring with default values
Adrian Bece for PROTOTYP

Posted on β€’ Originally published at blog.prototyp.digital

6 4

Javascript ES6: Destructuring with default values

This is a short, but very useful code snippet for destructuring variables with default values (if the value is undefined). Very useful snippet for avoiding errors caused by undefined variables.

In the following example, the options object is being destructured.

const {
    valFirst = 1,
    valSecond = "hello",
    valThird = false
  } = options;
Enter fullscreen mode Exit fullscreen mode

If a destructured value doesn't exist within the object, it will be assigned a default value. If it does exist within the object, it will be assigned the value from the object.

Thank you for taking the time to read this post. If you've found this useful, please give it a ❀️ or πŸ¦„, share and comment.

Top comments (3)

Collapse
 
athimannil profile image
Muhammed Athimannil β€’

helpful information πŸ‘Œ

Is it possible to rename the destructured variable with the default value?

does it work?

const { amount  =  0 : bill } = options;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rafaacioly profile image
Rafael Acioly β€’

This is not possible unfortunately

Collapse
 
athimannil profile image
Muhammed Athimannil β€’

Got it

const  { amount : bill = 0 } = options;
Enter fullscreen mode Exit fullscreen mode

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay