Rujal
Rujal

Reputation: 31

Can some one explain what's going on here? const {a={}}=b

Can someone explain the difference between

const {a={}}=b

and

let a={}
a=b

It works fine on const {a={}}=b but only empty object returns on the second one.

Upvotes: 1

Views: 91

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

The first snippet uses destructuring. It tries to take the a property out of the value in b. If no such property exists, a defaults to the empty object.

More verbosely

const {a={}}=b

is like

const a =
  b.a === undefined
  ? {}
  : b.a;

or

let a;
if (b.a === undefined) {
  a = {};
} else {
  a = b.a;
}

Your second snippet

let a={}
a=b

is completely different. It creates a single object, then discards it and reassigns a to whatever b contains.

Upvotes: 4

Related Questions