🌟chaining rules
Last updated
Last updated
JS ⟩ value ⟩ object ⟩ accessing properties ⟩ chaining rules
all chaining rules are depicted in the following diagrams.
replit:chaining rules
const { log } = console;
// ⭐ test if `x` is nullish
function isNullish(x) {
return x === undefined || x === null;
}
// ⭐ about ` a . b ?. c . d ?. e `
testAllCases({ logErrorMessage: false });
// ⭐ test all cases
function testAllCases({
logErrorMessage = false,
} = {}) {
// counts
let nullishCount = 0;
let nonnullishCount = 0;
let errorCount = 0;
// all cases: about ` a . b ?. c . d ?. e `
const cases = [
null,
{ b: null },
{ b: { c: null } },
{ b: { c: { d: null } } },
{ b: { c: { d: { e: null } } } },
{ b: { c: { d: { e: 'hi' } } } },
];
// iterate over all cases
for (const [i, a] of cases.entries()) {
try {
const value = a.b?.c.d?.e;
const nullish = isNullish(value);
nullish ? nullishCount += 1 : nonnullishCount += 1;
log(`case ${i + 1}: ${value} (${nullish ? 'N' : 'NN'})`);
} catch (err) {
log(`case ${i + 1}: ⛔ ${err.name}${logErrorMessage ? `: ${err.message}` : ''}`);
errorCount += 1;
}
}
// summary
log(` cases: ${cases.length} │ N NN // N : nullish`);
log(`───────────┽──────────── // NN: non-nullish`);
log(`• live: ${nullishCount + nonnullishCount} │ ${nullishCount} ${nonnullishCount}`);
log(`• dead: ${errorCount} │`);
}
// case 1: ⛔ TypeError
// case 2: undefined (N)
// case 3: ⛔ TypeError
// case 4: undefined (N)
// case 5: null (N)
// case 6: hi (NN)
// cases: 6 │ N NN // N : nullish
// ───────────┽──────────── // NN: non-nullish
// • live: 4 │ 3 1
// • dead: 2 │
⛔ possible errors:
SyntaxError:unexpected number❗ (👉 needs valid identifier)