xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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! ❌


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!

refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-05-31 21:28  xgqfrms  阅读(37)  评论(3编辑  收藏  举报