Further explanation on practice JS Challenge

Challenge link
Instructions

  1. Write a function, agreeOrDisagree(), that takes in two strings, and returns 'You agree!' if the two strings are the same and 'You disagree!' if the two strings are different.

My answer is following and it is correct

const agreeOrDisagree = (first, second) => {
  if (first === second) {
    return 'You agree!';
  } else if (first || second) {
    return 'You disagree!';
  }
}

And code solution is following:

const agreeOrDisagree = (first, second) => {
    if (first === second) {
        return 'You agree!'
    } else {
        return 'You disagree!'
    }
}

Did I went a bit off track writing else if (first || second) ? At the moment, that looked logical to me to do OR statement.

Since the or operator compares boolean’s rather than strings, essentially what you are doing is checking if either first or second are truthy statements. What this boils down to is that in the else if you are checking if either of first or second are strings that have content i.e. not the empty string "". If you wanted to do an else if that fit the actual criteria, then you would do else if (first !== second) and this would check if first and second are different.

However, due to how ifelse statements work, the else if condition would only be reached if the if condition was already false. So thinking about this, the if condition is only false if first and second are not identical strings (assuming strings are being passed in). Therefore if the else condition is being checked, it already implicitly means that first and second are not identical, therefore you don’t need to check this again. As such using a regular else statement is acceptable.

1 Like

Thank you for this explanation. I have some trouble to put all that together and understand what is being ask.