Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destructuring assignment default value [duplicate]

I am learning javascript and I got kind of stuck with ES6 syntax while trying to give a default value to a variable when destructuring. Basically, I am trying to assign a variable giving the value of an object's property to it and if the value is false/null/undefined, I want it to be an empty object. For example,

let foo = { 
            prop1: 'hello!',
            prop2: null 
           }

const prop1 = foo.prop1 || {}
const prop2 = foo.prop2 || {}

console.log(prop1) //  hello!
console.log(prop2) //  {}

๐Ÿ‘†This is what I want and ๐Ÿ‘‡ is ES6 sugar syntax I thought as equivalent to above(it doesn't work tho..)

let foo = { 
            prop1: 'hello!',
            prop2: null 
           }

const { prop1 = {} } = foo
const { prop2 = {} } = foo

console.log(prop1) // hello!
console.log(prop2) // null

but somehow, sometimes it seems working in React, but the other times it doesn't.. is it compatibility problem? so confusing!

like image 538
Jay Jeong Avatar asked Mar 12 '18 11:03

Jay Jeong


2 Answers

No, it is not compatibility problem.

Default value will works if there's no value, meaning that it will work if it is undefined. From your example, you're assigning null to prop2, and null is a defined value.

So it will work if your prop2 is not defined or assigned with undefined

let foo = { 
        prop1: 'hello!',
        prop2: undefined 
       }

const { prop1 = {} } = foo
const { prop2 = {} } = foo

console.log(prop1) // hello!
console.log(prop2) // {}
like image 28
Dimitrij Agal Avatar answered Oct 17 '22 04:10

Dimitrij Agal


You probably confused by the difference between null and undefined, For example:

const { dogName = 'snickers' } = { dogName: undefined }
console.log(dogName) // what will it be? 'snickers'!

const { dogName = 'snickers' } = { dogName: null }
console.log(dogName) // what will it be? null!

const { dogName = 'snickers' } = { dogName: false }
console.log(dogName) // what will it be? false!

const { dogName = 'snickers' } = { dogName: 0 }
console.log(dogName) // what will it be? 0!

Taken from: http://wesbos.com/destructuring-default-values/

like image 133
Shai Katz Avatar answered Oct 17 '22 03:10

Shai Katz