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

the power of js destructuring All In One

the power of js destructuring All In One

bad demo

// 👎
const getTemperature = (atticData) => atticData.celsius || 15;

// Object.prototype.toString.call(obj) === [object Object]
const getTemperature = (atticData) => atticData ? (atticData.celsius ? atticData.celsius : 15) : 15;

?. && ??

// 👍
const getTemperature = (atticData) => atticData?.celsius ?? 15;

object destructuring & default value

// 🚀 🎉
const getTemperature = ({ celsius = 15 } = {}) => celsius;
// ({ celsius = 15 } = {}) => celsius

getTemperature({celsius: 1});
// 1

getTemperature();
// 15

getTemperature({});
// 15

// ❌ null
getTemperature(null);
// Uncaught TypeError: Cannot read properties of null (reading 'celsius')

getTemperature(undefined);
// 15

getTemperature('');
// 15

getTemperature(NaN);
// 15

getTemperature([]);
// 15

getTemperature(false);
// 15

getTemperature(0);
// 15

getTemperature(new Map());
15
getTemperature(new Set());
15
getTemperature(Symbol());
15

refs

https://realworldjs.medium.com/never-use-the-dot-operator-in-javascript-ee0339d85fb

Array.isArray() ✅ & Object.isObject() ❌

https://attacomsian.com/blog/javascript-check-variable-is-object



©xgqfrms 2012-2020

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

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


posted @ 2021-10-01 23:43  xgqfrms  阅读(34)  评论(2编辑  收藏  举报