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, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15361078.html
未经授权禁止转载,违者必究!