Rondell Ben
Rondell Ben

Reputation: 41

Why do I get different boolean results, when they should be the same?

Why do I get different results when the results should be the same?

    let isPasswordValid = password => {
  if (!password.length <= 7) {
    return true;
  }
};

console.log(isPasswordValid("rondellallard"));  //true
console.log(isPasswordValid("passwordwfwfw"));  //true
console.log(isPasswordValid("ronde"));          //true
console.log(isPasswordValid("rondelltgh"));     //true
console.log(isPasswordValid("ronde42425"));     //true   

//Code page 2

  let isPasswordValid = password => {
  if (password.length >= 7) {
    return true;
  }
};

console.log(isPasswordValid("rondellallard")); //true
console.log(isPasswordValid("passwordwfwfw")); //true
console.log(isPasswordValid("ronde")); //undefined
console.log(isPasswordValid("rondelltgh")); //true
console.log(isPasswordValid("ronde42425")); //true

When I reverse the more than and less than signs I believe I should still get the same values. How ever when I do, that is not the result that I get. The 3rd value which is always supposed to be undefined in this example turns up to be tre in the first example, and I don't understand why.

Upvotes: 2

Views: 72

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50759

Because of the order of operations matters here (which is defined by operator precedence). With your first if-statement:

if(!password.length <= 7)

your password.length gets converted to a boolean due to the ! operator. Then, as this boolean value is being used in the context of an inequality, it will be converted to a number, where true becomes 1 and false becomes 0. So, your if condition will always evaluate to true as 0/1 <= 7.

In your second if-statement however,

if (password.length >= 7) {

you are actually checking the length of the string. Your function will return true if your password length is 7 or greater. However, you haven't defined what it should do if this is not the case, so by default, your function will return undefined implicitly.

Upvotes: 4

Related Questions