1

I was studying a project and I saw this kind of pattern:

handleValueChange = (e) => { const { target: { id, value } = {} } = e || {}; # some code .... 

I've never seen = within {} that comes after const, and I couldn't find any documentation online.

What is this type of syntax called? How does it work?

1
  • 1
    It's a default value in destructuring. Commented Jun 10, 2020 at 12:32

1 Answer 1

3

As mentioned in Destructuring assignment docs:

A variable can be assigned a default, in the case that the value unpacked from the object is undefined.

For example:

const {a = 10, b = 5} = {a: 3}; console.log(a); // 3 console.log(b); // 5

Here you can see b is undefined thus while destructuring the default value 5 is used for b.

In your case, if target is undefined while destructuring e, then an empty object {} will be used instead.

This is needed in cases e is undefined or null, else we will get an error like:

Cannot read property 'id' of undefined

const { target: { id, value } } = {}; console.log( id, value )

Using default value handles this scenario:

const { target: { id, value } = {} } = {}; console.log( id, value )

Sign up to request clarification or add additional context in comments.

1 Comment

perfect answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.