Truthy and Falsy Assignment

Please I am getting confused and I am not understanding a thing about truthy and falsy ASSIGNMENT… Please can anyone explain it properly??please… :tired_face: :tired_face: :weary: :persevere: :confounded:

I think the problem is with this part:

let defaultName = username || 'Stranger';

If you’ve done the lesson before this, you know that many things in javascript have truthy or falsy values, one of these is an empty string.
So what this means is that we can use these like a boolean.

let defaultName = username || 'Stranger';

Let’s look at this, how javascript would execute this line.

  1. declaring a variable named defaultName
  2. if username is an empty string, then it will act like a false value, if it is a string containing some text then it will act as true
  3. the string “Stranger” will act as a true since it is a string containing some text, which is truthy
  4. it uses the || operator(or) to check the two strings, and assigns the first truthy string to the defaultName variable

The 4. may be a little complicated so take a look at this:

//1. case, the user didn't log in so he or she doesn't have a username:
let username = "" // falsy
// 'Stranger' is truthy
let defaultName = username || 'Stranger' // defaultName is 'Stranger'

What happens here, is that since both string have either a truthy or falsy value, we can check the two, so what basically happens:

let username = false // it's an empty string so it's falsy
let defaultName = false || true // the 'Stranger' has some text in it so it's truthy
console.log(defaultName) // will log true to the console

The first truthy value was ‘Stranger’ so it used that to assign it to defaultName.
You can think of it as javascript converts the strings to either true or false, checks the two, then it converts them back into their original values.

The second case would be very similar:

// 2. case, the user is logged in
let username = "lolfail" // converted it will be truthy so acts like a true
// 'Stranger' converted will act like a true too
let defaultName = username || 'Stranger' // so: true || true

Javascript uses the first true value, so in this case, when it converted them back it will use the first true value, which is the username variable.

2 Likes