I have a variable and I want to return the value 0 if the original path returns as undefined.
I tried to do this with an IF statement inside the variable but this doesn't work.
Thank you for any help
const balance = wallet.balance if (balance === undefined || balance === null) {
console.log("Balance is null or undefined");
balance = 0;
};
The easiest way would be using the nullish coalescing operator ??:
const balance = wallet.balance ?? 0
Something closer to what you already wrote would be using a ternary:
const balance = wallet.balance == null ? 0 : wallet.balance
(Note that wallet.balance == null with loose comparison is a shorter way to check for both null and undefined at once.)
Of course you could also write an if, but then it would have be at its own line - and the variable would have to be non-const so it can be modified:
let balance = wallet.balance
if (balance == null) {
console.log("Balance is null or undefined");
balance = 0
}