Truthy and falsy assignment help

I don’t understand truthy and falsy conditional statements. Could someone explain this please? The example is below and this is the link to the course section https://www.codecademy.com/courses/introduction-to-javascript/lessons/control-flow/exercises/truthy-falsy-operators

Say you have a website and want to take a user’s username to make a personalized greeting. Sometimes, the user does not have an account, making the username variable falsy. The code below checks if username is defined and assigns a default string if it is not:

let username = ' ';
let defaultName; 
if (username) {  defaultName = username;
} else {  
defaultName = 'Stranger';
} 
console.log(defaultName); 
// Prints: Stranger

I don’t understand the defaultName and stranger bit.

This is another part of the example.

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:

let username = ' ';
let defaultName = username || 'Stranger'; 
console.log(defaultName); // Prints: Stranger

Because || or statements check the left-hand condition first, the variable defaultName will be assigned the actual value of username if it is truthy, and it will be assigned the value of 'Stranger' if username is falsy. This concept is also referred to as short-circuit evaluation.

1 Like

Hi. In JavaScript falsy values are false, 0, -0, 0n, "", null, undefined, and NaN. All other values are considered to be truthy.
So, in the example username is an empty string. Empty sting is a falsy value and if(username) will return false and execute the code in else statement.

2 Likes