let username = '';
let defaultName;
if (username) {
defaultName = username;
} else {
defaultName = 'Stranger';
}
console.log(defaultName); // Prints: Stranger
Truthy Falsy evaluations open a world of short-hand possibilities.
let username = '';
let defaultName = username || 'Stranger';
console.log(defaultName); // Prints: Stranger
If you combine your knowledge of logical operators you can use a short-hand for the code above. In a boolean condition, JavaScript assigns the truthy value to a variable if you use the || operator in your assignment:
Top comments (0)