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) // {}
You probably confused by the difference between null and undefined, For example:
Taken from: http://wesbos.com/destructuring-default-values/
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 assigningnull
toprop2
, andnull
is a defined value.So it will work if your
prop2
is not defined or assigned withundefined