Initializing Props
When working with data collections (like tracking user balances or scores), you often need to increment a specific key. However, if that property doesn’t exist yet, attempting to do math on it will result in NaN (Not a Number).
The Missing Property Problem
If you access a property that doesn’t exist using the dot operator, JavaScript returns undefined.
const balances = {
lane: 100,
breanna: 150
};
// 'bob' doesn't exist, so this evaluates to: undefined + 50 = NaN
balances.bob = balances.bob + 50;
The Solution: Safe Initialization
Because undefined is a “falsy” value in JavaScript, you can use the Logical NOT operator (!) to quickly check if a property is missing and initialize it to a safe default before proceeding.
const balances = {
lane: 100,
breanna: 150
};
// Check if 'bob' is falsy (undefined)
if (!balances.bob) {
// Initialize to 0
balances.bob = 0;
}
// Now it is safe to do math
balances.bob += 50;
console.log(balances.bob); // Output: 50