Truthy and falsy assignment

I’m back with what is probably a boneheaded question. I’m reviewing the module on conditional statements (JavaScript is kicking my butt and I realized I needed to go back to the top of the unit and review what I’d learned because it just wasn’t sticking), and here’s what it says:

“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:”

And then the code that follows looks like this:

let username = ‘’;
let defaultName;

if (username) {
defaultName = username;
} else {
defaultName = ‘Stranger’;
}

console.log(defaultName); // Prints: Stranger

What’s perplexing me is how “let defaultName” is a complete idea. Is it because the variable is assigned later with “defaultName = ‘Stranger’;”? Or is prefacing it with “let” enough for me to speak defaultName into existence? Thanks in advance for any input you can offer.

let username = ‘’;

We initialize a username variable and assign it to an empty string, which is considered falsy.

let defaultName;

Then, we initialize a defaultName variable, which has the value undefined.
It’s ok to have the defaultName variable initialized as undefined, because later on…

if (username) {
defaultName = username;
} else {
defaultName = ‘Stranger’;
}

We’re assigning defaultName to username if username is truthy (if it isn’t an empty string).
Or we’re assigning defaultName to ‘Stranger’ if username is falsy (if it’s an empty string).

Yes, you can speak defaultName into existence as undefined by using just “let”.

1 Like

Thank you so much for breaking it down like that! I understand now.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.