天天看點

ES6 destructuring assignment & default value & rename All In One

ES6 destructuring assignment & default value & rename All In One

ES6 destructuring assignment & default value & rename All In One

const settings = {
    speed: 1
};

const {
     speed = 1,
     width = 100,
} = settings;

console.log(speed); 
// 1 - comes from settings object
console.log(width);
// 100 - fallback to default

      
const person = {
  first: 'eric',
  // last: undefined,
};

const {
  first: firstName,
  last: lastName = 'Eric' ,
} = person;

console.log(firstName); 
// xgqfrms
console.log(lastName); 
// Eric

      

Because ES6 destructuring assignment ​

​default values​

​ only kick in if the value is ​

​undefined​

​ ✅; ​

​null​

​, ​

​false​

​ and ​

​0​

​ are all still values! ❌

ES6 destructuring assignment & default value & rename All In One
const { dogName = '(Snoopy' } = { dogName: undefined }
console.log(dogName);
// what will it be? '(Snoopy'! ✅

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!